Note: This article is available in Chinese only. 本文暂无英文版本。
View original
思路:
一个元素入队的时候直接插入到stack1中。。。
一个元素出队的时候。。。如果stack2不为空。。stack2顶的元素就是要出队的。。
如果stakc2为空。。。就将stack1清空,按照元素出栈的顺序依次入栈到stack2
1class Solution
2{
3public:
4 void push(int node) {
5 stack1.push(node);
6
7 }
8
9 int pop() {
10 if (stack2.size()!=0)
11 {
12 int ret = stack2.top();
13 stack2.pop();
14 return ret;
15 }
16 while (!stack1.empty())
17 {
18 int val = stack1.top();
19 stack1.pop();
20 stack2.push(val);
21 }
22 if (stack2.size()!=0)
23 {
24 int ret = stack2.top();
25 stack2.pop();
26 return ret;
27 }
28 return -1;
29
30 }
31
32private:
33 stack<int> stack1;
34 stack<int> stack2;
35};