兩個棧實現一個隊列
使用棧實現隊列的下列操作:
- push(x) – 將一個元素放入隊列的尾部。
- pop() – 從隊列首部移除元素。
- peek() – 返回隊列首部的元素。
- empty() – 返回隊列是否爲空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
說明:
- 你只能使用標準的棧操作 – 也就是隻有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
- 你所使用的語言也許不支持棧。你可以使用 list 或者 deque(雙端隊列)來模擬一個棧,只要是標準的棧操作即可。
- 假設所有操作都是有效的 (例如,一個空的隊列不會調用 pop 或者 peek 操作)。
參考答案
class MyQueue {
stack<int> s1; //進入的棧
stack<int> s2; //退出的棧
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int val = peek();
s2.pop();
return val;
}
/** Get the front element. */
int peek() {
if(s2.empty()){
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
}
return s2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return s1.empty() && s2.empty();
}
};