0%

用两个栈实现队列

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

栈为先入后出,队列为先出后入,我们将全部入栈再全部出栈视为函数X,将全部入队再全部出队视为函数Y,则Y(seq)=X(X(seq))。故可使用2个栈,入队时将元素压入栈a,出队时将栈a中的元素全部弹出并压入栈b,再从栈b出栈。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution
{
public:
void push(int node) {
stack1.push(node);
}

int pop() {
int result;
if (stack2.size() > 0)
{
result = stack2.top();
stack2.pop();
}
else
{
if (stack1.size() == 0)
{
result = -1;
}
else
{
while (stack1.size() > 0)
{
stack2.push(stack1.top());
stack1.pop();
}
result = stack2.top();
stack2.pop();
}
}
return result;
}

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