[AcWing. 20. 用两个栈实现队列]

请用栈实现一个队列,支持如下四种操作:

  • push(x) – 将元素x插到队尾;
  • pop() – 将队首的元素弹出,并返回该元素;
  • peek() – 返回队首元素;
  • empty() – 返回队列是否为空;

注意:

  • 你只能使用栈的标准操作:push to toppeek/pop from top, sizeis empty
  • 如果你选择的编程语言没有栈的标准库,你可以使用list或者deque等模拟栈的操作;
  • 输入数据保证合法,例如,在队列为空时,不会进行pop或者peek等操作;

数据范围

每组数据操作命令数量 [0,100]

样例

1
2
3
4
5
6
7
MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false

算法思想

image-20240611202459520

image-20240611202525947

借助辅助栈,可以让主栈只剩下一个元素,然后拿一个变量保存它后执行pop或者peek逻辑返回它。

过程中,拿变量保存它之后,需要将辅助栈中的元素们回到主栈中

代码实现

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class MyQueue {
public:
int stk[100010];
int tmp_stk[100010];
int tt;
int tmp_tt;

/** Initialize your data structure here. */
MyQueue() {
tt = 0;
tmp_tt = 0;
}

/** Push element x to the back of queue. */
void push(int x) {
// 0不用,直接用1
stk[++ tt] = x;
}

/** Removes the element from in front of queue and returns that element. */
int pop() {
// stk只留下1个,其它全部移到辅助栈tmp_stk里去
while(tt > 1){
// tmp_stk入栈,stk出栈
tmp_stk[++ tmp_tt] = stk[tt --];
}

int k = stk[tt --];

// 移回去
while(tmp_tt){
stk[++ tt] = tmp_stk[tmp_tt --];
}

return k;
}

/** Get the front element. */
int peek() {
// stk只留下1个,其它全部移到辅助栈tmp_stk里去
while(tt > 1){
// tmp_stk入栈,stk出栈
tmp_stk[++ tmp_tt] = stk[tt --];
}

int k = stk[tt];

// 移回去
while(tmp_tt){
stk[++ tt] = tmp_stk[tmp_tt --];
}

return k;
}

/** Returns whether the queue is empty. */
bool empty() {
return !tt;
}
};

/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/