队列是一种特殊的线性表,它只允许在表的前端进行删除操作,而在表的后端进行插入操作。
LinkedList类实现了Queue接口,可以把LinkedList当成Queue来用。
队列的三个方法:
思路:push的时候,先直接从队列末端offer上这个元素,在队列中元素大于2之后,每次offer之后都做一次将队列内元素reverse的操作,这样就可以用一个队列实现栈
复杂度分析:这个算法需要从队列中出队n个元素,同时还需要入队n个元素到队列,其中 n 是栈的大小。这个过程总共产生了 2n + 1 步操作。链表中插入操作和移除操作的时间复杂度为 O(1),因此时间复杂度为 O(n)。
代码:
class MyStack {
private 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) {
this.queue.offer(x);
for(int i = 1;i<this.queue.size();i++){
this.queue.offer(this.queue.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return this.queue.poll();
}
/** Get the top element. */
public int top() {
return this.queue.element();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return this.queue.isEmpty();
}
}
原文:https://www.cnblogs.com/swifthao/p/12764606.html