Description
Implement the following operations of a stack using queues.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
Notes:
- You must use only standard operations of a queue -- which means only
push to back
,peek/pop from front
,size
, andis empty
operations are valid. - Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.
Solution
Two queues, push O(n), other functions O(1)
每次push时把所有元素折腾成逆进入顺序的。感觉有点像递归啊:
reverse(a, n)代表把a中n各元素调整成逆序,用递归来做就是返回a[n] append reverse(a, n - 1)。
class MyStack {
private Queue<Integer> q1;
private Queue<Integer> q2;
/** Initialize your data structure here. */
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
if (q1.isEmpty()) {
q1.offer(x);
while (!q2.isEmpty()) {
q1.offer(q2.poll());
}
} else {
q2.offer(x);
while (!q1.isEmpty()) {
q2.offer(q1.poll());
}
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q1.isEmpty() ? q2.poll() : q1.poll();
}
/** Get the top element. */
public int top() {
return q1.isEmpty() ? q2.peek() : q1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q1.isEmpty() && q2.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
Optimized: One queue, push O(n), other functions O(1)
其实一个queue就够了啦。
class MyStack {
Queue<Integer> q;
/** Initialize your data structure here. */
public MyStack() {
q = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
q.offer(x);
for (int i = 0; i < q.size() - 1; ++i) {
q.offer(q.poll()); // rotate prev elements to the tail
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return q.poll();
}
/** Get the top element. */
public int top() {
return q.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/