栈--用一个队列实现栈(leetcode 225)

队列基础知识

队列是一种特殊的线性表,它只允许在表的前端进行删除操作,而在表的后端进行插入操作。

LinkedList类实现了Queue接口,可以把LinkedList当成Queue来用。

队列的三个方法:

  • offer方法:一些队列有大小限制,因此如果想在一个满的队列中加入一个新项,多出的项就会被拒绝。这时新的 offer 方法就可以起作用了。它不是对调用 add() 方法抛出一个 unchecked 异常,而只是得到由 offer() 返回的 false。
  • poll方法:remove() 和 poll() 方法都是从队列中删除第一个元素。remove() 的行为与 Collection 接口的版本相似, 但是新的 poll() 方法在用空集合调用时不是抛出异常,只是返回 null。因此新的方法更适合容易出现异常条件的情况。
  • element方法:element() 和 peek() 用于在队列的头部查询元素。与 remove() 方法类似,在队列为空时, element() 抛出一个异常,而 peek() 返回 null。

用队列实现栈

方法1:用一个队列实现栈

思路: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