使用队列来实现栈
class MyStack {
Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
this.queue=new LinkedList<Integer>();
}
/** Push element x onto stack. */
public void push(int x) {
//2
// Queue<Integer> tmp=new LinkedList<Integer>();
// tmp.add(x);
// while(!queue.isEmpty()){
// tmp.add(queue.poll());
// }
// while(!tmp.isEmpty()){
// queue.add(tmp.poll());
// }
//3
// queue=tmp;
//1.
queue.add(x);
for (int i=0;i<queue.size()-1;i++){
queue.add(queue.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
只实现push,有三种方法:
1.直接将新的数加入到队尾,然后将前面数依次出队,再依次添加到队中。117ms
2.采用一个临时队列tmp,将新的数加入到tmp中,之后将queue中的数全部出队加入到tmp中,再使得queue=tmp。126ms
3.同二方法,但是再使用循环将tmp全部出队加入到queue中。 108ms