leetcode用队列实现栈

1.双队列

队列q1用来存放新入栈的元素,队列q2存放入队元素的逆序

入栈时,队列q1添加元素,当q2不为空时,依次取出q2中的元素添加到q1中,然后交换q1与q2的值。此时q2队首元素即是栈顶元素

代码如下:

class MyStack {
    queue<int> q1;
    queue<int> q2;
public:
    /** Initialize your data structure here. */
    MyStack() {

    }
    
    /** Push element x onto stack. */
    void push(int x) {
      q1.push(x);//
      while(!q2.empty())
      {
          q1.push(q2.front());
          q2.pop();
      }//此时q1中为元素入队的逆序,q2为空
      //交换q1,q2
      queue temp=q1;
      q1=q2;
      q2=temp;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int res=q2.front();//q2队首位最早入队的元素
        q2.pop();
        return res;
       
    }
    
    /** Get the top element. */
    int top() {
       return q2.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
       if(q1.empty()&&q2.empty())
         return true;
        return false;
    }
};

/**
 * 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();
 */

2.单队列

当有元素入队时,先计算当前队列的长度,然后将元素入队;

然后依次取出原队列的元素重新入队。此时,队列中存放的是入队元素的逆序,队首即为栈顶元素

如1 2 3 4 5

1入栈,队列为1

2入栈 原队列长度为1,取出1重新入队,队列为2 1

3入栈,原队列长度为2,取出2 1重新入队,队列为3 2 1

4入栈,原队列长度为3 取出3 2 1 重新入队,队列为4 3 2 1 

5入栈,原队列长度为4,取出4 3 2 1 重新入队,队列为5 4 3 2 1 

代码如下:

class MyStack {
    queue<int> q1;
public:
    /** Initialize your data structure here. */
    MyStack() {

    }
    
    /** Push element x onto stack. */
    void push(int x) {
      int  size=q1.size();
      q1.push(x);//
      while(size--)
      {
          int temp=q1.front();
          q1.pop();
           q1.push(temp);
      }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int res=q1.front();//q1队首位最早入队的元素
        q1.pop();
        return res;
       
    }
    
    /** Get the top element. */
    int top() {
       return q1.front();
    }
    
    /** Returns whether the stack is empty. */
    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();
 */

猜你喜欢

转载自blog.csdn.net/qq_38196982/article/details/105142418