【leetcode】用队列实现栈c++

题目描述:
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。

实现 MyStack 类:

void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。

注意:

你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

示例:

输入:
[“MyStack”, “push”, “push”, “top”, “pop”, “empty”]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]

解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False

提示:

1 <= x <= 9 最多调用100 次 push、pop、top 和 empty 每次调用 pop 和 top 都保证栈不为空

代码:

#include<queue>
class MyStack {
    
    
public:
    queue<int> q1,q2;
    int l=0;
    /** Initialize your data structure here. */
    MyStack() {
    
    
    
    }
    
    /** Push element x onto stack. */
    void push(int x) {
    
       
        q1.push(x);
        l=l+1;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
    
    
        int topval = q1.back();
        int n1=q1.size();
        if(n1!=1){
    
    
            for(int i=0;i<n1-1;i++){
    
     //q2记录除了q1最后一个元素外的所有元素
                int val = q1.front();
                q2.push(val);
                q1.pop();
            }
            int n2=q2.size();
            for(int i=0;i<n2;i++){
    
    
                int val = q2.front();
                q1.push(val);
                q2.pop();
            }
        }
        l=l-1;
        return topval;
    }
    
    /** Get the top element. */
    int top() {
    
    
        return q1.back();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
    
    
        return l==0?true:false; //l=0返回true
    }
};

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

队列先进先出(尾巴进头出),栈先进后出(尾巴进尾巴出)。用两个队列是因为queue读取元素只能通过按顺序获取front()元素,再pop到下一个元素,不能直接用下标获取。

实现栈pop时,用第二个队列来记录第一个队列pop掉的元素再存入第一个队列即可。

第二个队列充当中间变量。

猜你喜欢

转载自blog.csdn.net/qq_40315080/article/details/116174425