用列表实现栈

此博客链接:https://www.cnblogs.com/ping2yingshi/p/12622547.html

用列表实现栈(89min)

题目链接:https://leetcode-cn.com/problems/implement-stack-using-queues/

使用队列实现栈的下列操作:

push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
注意:

你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

题解:

        说明:

                 1.栈是“先进后出”,队列是“先进先出”。

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

                3.LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。

        方法:用队列模仿栈每次入栈一个数字都在栈顶:一个数入队时,把前面的数字都出队再重新入队,此时刚进入的队列就在队头位置了。

        思路:

                 1.进队:数字刚进入队列时,把除了这个数以外的数字,队列中所有的数字都出队列,并把数字按照出队顺序重新进队列。这样可以保证每次刚进队列的数字在对头,模仿在栈中的栈顶。

                  说明:队列中add也是入栈操作,但是当队列满时,会抛出异常,而offer只是返回false。remove也是出队列操作,当时当队列空时,使用remove会抛出异常,而poll只是返回null.

                 2.出队:使用poll把队列中第一个元素出队并删除这个元素。

                 3.使用peek取出队列中第一个元素.

代码如下:

class MyStack {
    Queue <Integer> queue;
    /** Initialize your data structure here. */
    public MyStack() {
       queue=new LinkedList<>();

    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue.offer(x);
        int len=queue.size();
        for(int i=0;i<len-1;i++)
           {
               //x前面元素出队
               queue.offer(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();
        

    }
}

 

     

posted @ 2020-04-02 19:45  萍2樱释  阅读(326)  评论(0编辑  收藏  举报