《剑指offer》用两个栈实现队列
一、题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
二、输入描述
三、输出描述
四、牛客网提供的框架
class Solution
{
public:
void push(int node) {
}
int pop() {
}
private:
stack<int> stack1;
stack<int> stack2;
};
五、解题思路
使用两个堆栈,其中一个是用来存储数据,另外一个是辅助“出队列”作用。入队是,保存到堆栈stack1中。这时堆栈里数据的顺序刚好跟队列的相反。出队列时,通过辅助栈stack2的作用,取出栈底元素。出队列后,再把辅助栈的数据放回stack1中。
六、代码
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int len = stack1.size();
if(len < 1) return -1;
for(int i = 0; i < len - 1; i++)
{
int top = stack1.top();
stack2.push(top);
stack1.pop();
}
int headNum = stack1.top();
stack1.pop();
for(int i = 0; i < len - 1; i++)
{
int top = stack2.top();
stack1.push(top);
stack2.pop();
}
return headNum;
}
private:
stack<int> stack1;
stack<int> stack2;
};

浙公网安备 33010602011771号