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.
Example:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
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:
思路:
首先想到用两个栈,每次peek/pop时候先倒灌到helperStack取top,再灌回去。但是如果连续操作peek/pop的时候就浪费很多灌栈的动作。可以伺机而动,由下一步动作决定要不要灌回去。所以相当于一个栈用来pop,一个用来push。是pop/peek就保证在popStakck当中,是push就保证在pushStack当中。省掉中间变量,省掉一半时间。
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
while(!popStack.empty()){
pushStack.push(popStack.top());
popStack.pop();
}
pushStack.push(x);
return;
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
while(!pushStack.empty()){
popStack.push(pushStack.top());
pushStack.pop();
}
int t = popStack.top();
popStack.pop();
return t;
}
/** Get the front element. */
int peek() {
while(!pushStack.empty()){
popStack.push(pushStack.top());
pushStack.pop();
}
return popStack.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return popStack.empty() && pushStack.empty();
}
private:
stack<int> popStack, pushStack;
};
/**
* 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();
* bool param_4 = obj.empty();
*/
方法2:
grandyang:http://www.cnblogs.com/grandyang/p/4626238.html
grandyang的做法,好处就是只需要manipulate push的操作,完全模拟queue的入队:每次push先倒灌tmp,加入x,再灌回去。模拟完全由push负责。
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {}
/** Push element x to the back of queue. */
void push(int x) {
stack<int> tmp;
while (!st.empty()) {
tmp.push(st.top()); st.pop();
}
st.push(x);
while (!tmp.empty()) {
st.push(tmp.top()); tmp.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int val = st.top(); st.pop();
return val;
}
/** Get the front element. */
int peek() {
return st.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return st.empty();
}
private:
stack<int> st;
};