leetcode-232-Implement-Queue-using-Stacks

描述


Implement the following operations of a queue using stacks.

push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.

分析


用堆栈实现队列,与leetcode-225-Implement-Stack-using-Queues类似。这里的思路是用两个队列(s1, s2)来模拟堆栈的操作。这个问题可以抽象为要取一杯子饼干杯底的那块,我们可以将这杯饼干倒入到一个空杯中。push(x)操作,用stack的push即可,empty()操作,当s1,s2都是empty(),队列即是empty(),peek函数的含义是取得队首的元素(即杯底),如果s2中有元素,那么就取出,没有,就执行一次「倒空杯」操作。

解决方案1(C++)


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
class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
s1.push(x);
}

// Removes the element from in front of queue.
void pop(void) {
this->peek();
return s2.pop();
}

// Get the front element.
int peek(void) {
if(!s2.empty()) return s2.top();
while(!s1.empty()){
int temp = s1.top();
s2.push(temp);
s1.pop();
}
return s2.top();
}

// Return whether the queue is empty.
bool empty(void) {
return s1.empty() && s2.empty();
}
private:
stack<int> s1, s2;
};

解决方案2(Golang)


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
import "container/list"

type MyQueue struct {
Stack1 *list.List
Stack2 *list.List
}


func Constructor() MyQueue {
result := MyQueue{}
result.Stack1 = list.New()
result.Stack2 = list.New()
return result
}


func (this *MyQueue) Push(x int) {
this.Stack1.PushBack(x)
}


func (this *MyQueue) Pop() int {
this.Peek()
result := this.Stack2.Back()
this.Stack2.Remove(result)
intResult, _ := result.Value.(int)
return intResult
}


func (this *MyQueue) Peek() int {
if this.Stack2.Len() == 0 {
for this.Stack1.Len() != 0 {
now := this.Stack1.Back()
this.Stack1.Remove(now)
this.Stack2.PushBack(now.Value.(int))
}
}
result := this.Stack2.Back()
intResult, _ := result.Value.(int)
return intResult
}


func (this *MyQueue) Empty() bool {
if this.Stack1.Len() == 0 && this.Stack2.Len() == 0 {
return true
}
return false
}


/**
* Your MyQueue object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Peek();
* param_4 := obj.Empty();
*/

相关问题


题目来源