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.
Example:
MyStack stack = new MyStack(); stack.push(1); stack.push(2); stack.top(); // returns 2 stack.pop(); // returns 2 stack.empty(); // returns false
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).
这题目有点水。应该是cc150的原题。不知道意义何在。原题应该是没有top这个东西的。加了top稍微加了一点难度。
原本的做法也很简单,push是照常push的,复杂度O(n)。但是pop就不是照常poll了。如果你的queue里面有n个元素,那么你就poll n - 1 个,那剩下那个自然就是最后那个,符合stack LIFO的原理。poll出去的那些其实就直接push回去就行了。
譬如原来是 1 -> 2 -> 3 -> 4 -> 5。 你poll了四个并且把他们又push进来之后就成了 5 -> 1 -> 2 -> 3 -> 4。头元素5自然就是最后一个。top稍微增加了一点难度,你需要一个临时变量记录一下,譬如说你如果call top,你就做pop那样的操作并且记录一下头元素,如果再call top或者pop,如果有top元素的记录,就不再操作直接返回top。给出代码如下:
/** Initialize your data structure here. */
Integer top;
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<Integer>();
top = null;
}
/** Push element x onto stack. */
public void push(int x) {
if (top != null) {
queue.add(top);
top = x;
} else {
top = x;
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int res = top();
top = null;
return res;
}
/** Get the top element. */
public int top() {
if (top == null) {
int popTimes = queue.size() - 1;
while (popTimes > 0) {
queue.add(queue.poll());
popTimes--;
}
top = queue.poll();
}
return top;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return top == null && queue.isEmpty();
}