class MyStack {
Queue<Integer> queue1, queue2;
/** Initialize your data structure here. */
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
while (!queue1.isEmpty()) {
queue2.offer(queue1.poll());
}
queue1.offer(x);
while (!queue2.isEmpty()) {
queue1.offer(queue2.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue1.poll();
}
/** Get the top element. */
public int top() {
return queue1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.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();
*/
Analysis
push的时间复杂度为O(N), 其余O(1).
Ver.2
其实用一个queue就行。把新元素先塞进去,然后把原来的元素依次扔到queue尾。
// Push element x onto stack.
public void push(int x)
{
queue.add(x);
for(int i=0;i<queue.size()-1;i++)
{
queue.add(queue.poll());
}
}