225. 用队列实现栈

使用队列实现栈的下列操作:

  • push(x) – 元素 x 入栈
  • pop() – 移除栈顶元素
  • top() – 获取栈顶元素
  • empty() – 返回栈是否为空

Solution:

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
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {

}

/** Push element x onto stack. */
void push(int x) {
std::queue<int> temp_queue;
temp_queue.push(x);
while(!data_queue.empty()){
temp_queue.push(data_queue.front());
data_queue.pop();
}
while(!temp_queue.empty()){
data_queue.push(temp_queue.front());
temp_queue.pop();
}
}

/** Removes the element on top of the stack and returns that element. */
int pop() {
int x = data_queue.front();
data_queue.pop();
return x;
}

/** Get the top element. */
int top() {
return data_queue.front();
}

/** Returns whether the stack is empty. */
bool empty() {
return data_queue.empty();
}

private:
std::queue<int> data_queue;
};
核心思想:让新进来的元素始终在队列的头位置。

所以需要一个临时的队列。先让push进来的元素进去临时队列里。再让原来的队列的元素全进去临时队列,这样就保证了队列的头位置始终是新进来的元素。再将临时队列的所有元素push回原队列。

push操作