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.
我使用单个queue 这样 push,empty是O(1),pop,top是O(n)。一开始使用了ArrayDeque 发现效率比较低 ,使用 LinkedList之后效率高多了。具体的原因可能需要看源码注解了。
class MyStack {
LinkedList<Integer> queue = new LinkedList <>();
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
queue.add(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
for(int i = 0 ;i<queue.size()-1;i++)
{
queue.add(queue.poll());
}
return queue.poll();
}
/** Get the top element. */
public int top() {
for(int i = 0 ;i<queue.size()-1;i++)
{
queue.add(queue.poll());
}
int result = queue.poll();
queue.add(result);
return result ;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.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();
*/