232. 用栈实现队列

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

  • push(x) – 将一个元素放入队列的尾部。
  • pop() – 从队列首部移除元素。
  • peek() – 返回队列首部的元素。
  • 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
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {

}
/** push all element of _s1 to _s2*/
void pushTos2(){
if(_s1.empty()) return;
while(!_s1.empty()){
_s2.push(_s1.top());
_s1.pop();
}
}
/** Push element x to the back of queue. */
void push(int x) {
return _s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(_s2.empty()) pushTos2();
int a = _s2.top();
_s2.pop();
return a;
}
/** Get the front element. */
int peek() {
if(_s2.empty()) pushTos2();
return _s2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return _s1.empty() && _s2.empty();
}
private:
std::stack<int> _s1;
std::stack<int> _s2;
};

使用两个栈来实现堆。

  • 在做push操作的时候,直接push进第一个栈。
  • 当要pop时,先检查第二栈是否为空,如果为空,就把第一个栈的元素全push进第二个栈,这是原本在第一个栈栈底的元素,就到了第二个栈的栈顶(相当于翻了个个)。这时就可以pop出去了。

下面的函数实现的就是专门将第一个栈的元素全部push进第二栈的功能。

1
2
3
4
5
6
7
8
/** push all element of _s1 to _s2*/
void pushTos2(){
if(_s1.empty()) return;
while(!_s1.empty()){
_s2.push(_s1.top());
_s1.pop();
}
}

  • 当peek时,如果第二个栈已经没有元素。 也需要把第一个栈的元素“倒”进来,再进行peek();
  • empty:当两个栈都没有元素才算空。