代码随想录算法训练营第十天 |232. 用栈实现队列、225. 用队列实现栈

63 阅读1分钟

代码随想录算法训练营第十天 |232. 用栈实现队列、225. 用队列实现栈

232. 用栈实现队列

题目链接:232. 用栈实现队列

  • 一个栈用来暂存,一个栈用来push和pop
  •  class MyQueue {
     public:
         // stack<int> s1;
         // stack<int> s2;
         MyQueue() {
             stack<int> s1;
             stack<int> s2;
         }
         
         void push(int x) {
             s1.push(x);
         }
         
         int pop() {
             while(!s1.empty() && s1.size() > 1) {
                 s2.push(s1.top());
                 s1.pop();
             }
             int x = s1.top();
             s1.pop();
             while(!s2.empty()) {
                 s1.push(s2.top());
                 s2.pop();
             }
             return x;
         }
         
         int peek() {
             while(!s1.empty() && s1.size() > 1) {
                 s2.push(s1.top());
                 s1.pop();
             }
             int x = s1.top();
             while(!s2.empty()) {
                 s1.push(s2.top());
                 s2.pop();
             }
             return x;
         }
         
         bool empty() {
             return s1.empty();
         }
     };
     ​
     /**
      * Your MyQueue object will be instantiated and called as such:
      * MyQueue* obj = new MyQueue();
      * obj->push(x);
      * int param_2 = obj->pop();
      * int param_3 = obj->peek();
      * bool param_4 = obj->empty();
      */
    

225. 用队列实现栈

题目链接:225. 用队列实现栈

  • 需要清楚java链表和Queue的接口,que.peek()是队首元素
 class MyStack {
 public:
     queue<int> q1;
     queue<int> q2;
     MyStack() {
     }
     
     void push(int x) {
         q1.push(x);
     }
     
     int pop() {
         while(!q1.empty() && q1.size() > 1) {
             q2.push(q1.front());
             q1.pop();
         }
         int x = q1.front();
         q1.pop();
         while(!q2.empty()) {
             q1.push(q2.front());
             q2.pop();
         }
         return x;
     }
     
     int top() {
          while(!q1.empty() && q1.size() > 1) {
             q2.push(q1.front());
             q1.pop();
         }
         int x = q1.front();
         q2.push(q1.front());
         q1.pop();
         while(!q2.empty()) {
             q1.push(q2.front());
             q2.pop();
         }
         return x;
     }
     
     bool empty() {
         return q1.empty();
     }
 };
 ​
 /**
  * Your MyStack object will be instantiated and called as such:
  * MyStack* obj = new MyStack();
  * obj->push(x);
  * int param_2 = obj->pop();
  * int param_3 = obj->top();
  * bool param_4 = obj->empty();
  */