两个栈实现一个队列

  • push:直接push进stIn
  • pop:

    • 如果stOut不为空,直接pop
    • 如果stOut为空,先将stIn中所有元素push进stIn,再pop

      1. // push的时候直接push进st1,pop的时候如果st2不为空,直接出栈;如果st1为空,将st1的元素全部push进st2后,再出栈。
      2. class CQueue {
      3. public:
      4. CQueue() {
      5. }
      6. void appendTail(int value) {
      7. stIn.push(value);
      8. }
      9. int deleteHead() {
      10. if (stOut.empty()) {
      11. if (stIn.empty()) return -1;
      12. while (!stIn.empty()) {
      13. stOut.push(stIn.top());
      14. stIn.pop();
      15. }
      16. }
      17. int num = stOut.top();
      18. stOut.pop();
      19. return num;
      20. }
      21. int top() {
      22. int num = deleteHead(); // 代码复用
      23. stOut.push(num);
      24. return num;
      25. }
      26. int empty() {
      27. return (stIn.empty() && stOut.empty());
      28. }
      29. private:
      30. stack<int> stIn;
      31. stack<int> stOut;
      32. };

      队列实现栈

      pop实现,将队列队首的元素一个个弹出重新放入队列的队尾,只留下原来队列中的最后一个元素弹出
      push就是直接将元素插入队尾

      class MyStack {
      public:
      MyStack() {
      
      }
      
      void push(int x) {
         que.push(x);
      }
      
      int pop() {
         if (que.empty()) return -1;
         int cnt = que.size() - 1;
         while (cnt--) {
             que.push(que.front());
             que.pop();
         }
         int res = que.front();
         que.pop();
         return res;
      }
      
      int top() {
         int res = pop();
         que.push(res);
         return res;
      }
      
      bool empty() {
         return que.empty();
      }
      queue<int> que;
      };