问题:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
输入:两个栈
输出:队列的push和pop操作
思路:
入队列时,压进stack1。
出队列时,判断stack2是否为空:
- 如果为空,则将stack1全部元素弹出,压入stack2,
- 如果不为空,则从stack2弹出一个元素。
代码:
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int result;
if(!stack2.empty())
{
result = stack2.top();
stack2.pop();
}
else
{
int temp;
while(!stack1.empty())
{
temp = stack1.top();
stack1.pop();
stack2.push(temp);
}
if(!stack2.empty())
{
result=stack2.top();
stack2.pop();
}
else
return -1;
}
return result;
}
private:
stack<int> stack1;
stack<int> stack2;
};
复杂度分析:时间复杂度为O(n),空间复杂度也为O(n).