leetcode解题: Implement Queue using Stacks (232)

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.
Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

解法1:Two Queue

stack和queue的区别是前者是FILO, 后者是FIFO, 如果用另外一个stack去反倒回来就得到了queue一样的效果。
实现起来,用一个buffer stack存储应该的顺序,peek和pop都应该从buffer中取,如果读取buffer的时候为空的话,则需要把数据从原stack移到buffer。
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
32
33
34
35
36
37
38
class Queue {
private:
stack<int> mstack;
stack<int> buffer;
public:
// Push element x to the back of queue.
void push(int x) {
mstack.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
if (buffer.empty()) {
while (!mstack.empty()) {
buffer.push(mstack.top());
mstack.pop();
}
}
buffer.pop();
}
// Get the front element.
int peek(void) {
if (buffer.empty()) {
while (!mstack.empty()) {
buffer.push(mstack.top());
mstack.pop();
}
}
return buffer.top();
}
// Return whether the queue is empty.
bool empty(void) {
return mstack.empty() && buffer.empty();
}
};

Java
只有在push的时候,如果当前的stack里面存在元素的话,先把元素存在另外一个stack里面。然后把要push的元素push了之后再把buffer里面的元素放回stack。

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
class MyQueue {
/** Initialize your data structure here. */
Stack<Integer> stack;
public MyQueue() {
stack = new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
Stack<Integer> temp = new Stack<Integer>();
while (!stack.isEmpty()) {
temp.push(stack.pop());
}
stack.push(x);
while (!temp.isEmpty()) {
stack.push(temp.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return stack.pop();
}
/** Get the front element. */
public int peek() {
return stack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/