C++ 栈实现队列

牛客编程题

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
//思路:如果我们将元素压入栈A,然后弹出栈A的元素压入栈B,再弹出栈B元素,注意的是向栈B压入新元素,需要保证此时栈B为空,不然元素弹出顺序出错
class Solution
{
public:
void push(int node) {
stack1.push(node);
//stack2.push(stack1.top);
}


int pop() {
if (stack2.empty()){
while (!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
int value = stack2.top();
stack2.pop();
return value;


}


private:
stack<int> stack1;
stack<int> stack2;
};


猜你喜欢

转载自blog.csdn.net/S_powerStone/article/details/76012909