• 225. Implement Stack using Queues


    Implement the following operations of a stack using queues.

    • push(x) -- Push element x onto stack.
    • pop() -- Removes the element on top of the stack.
    • top() -- Get the top element.
    • empty() -- Return whether the stack is empty.

    Notes:

      • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
      • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
      • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
      • 思路:用队列实现栈,队列和栈的区别就是,栈是先进后出的,队列是先进先出的,队头元素相当于栈顶元素,那么栈的实现就好比是把队列先进去的那些又拿出来重新从后面进一次。
        public class MyStack {
            Queue<Integer>queue=new LinkedList<>();
            /** Initialize your data structure here. */
            public MyStack() {
                
            }
            
            /** Push element x onto stack. */
            public void push(int x) {
                queue.add(x);//队列和linkedlist一样的
               for(int i=0;i<queue.size()-1;i++)
               {
            	   queue.add(queue.remove());//把队头元素转为栈顶元素
               }
            }
            
            /** Removes the element on top of the stack and returns that element. */
            public int pop() {
                 return queue.remove();//出队的反而是最后入队的元素
            }
            
            /** Get the top element. */
            public int top() {
                return queue.peek();//对头就是栈顶,即最后一个元素
            }
            
            /** Returns whether the stack is empty. */
            public boolean empty() {
                return queue.isEmpty();
            }
        }
        

          队列和栈之间是很巧妙的关系,队列转换为栈可以这样做,但是堆栈转换为队列的方法这样可不行。

  • 相关阅读:
    奇迹银桥「1」
    20190729-“退役”专场
    20190727-只是睡着了
    $mathcal{Miemeng}$的病态码风计划
    20190725-Silly
    作业-[luogu4396][AHOI2013]-莫队
    数学网学笔记
    20190722-Moni和Boly的故事
    数学学习笔记
    20190719-FirstZero
  • 原文地址:https://www.cnblogs.com/zhangfanxmian/p/6929922.html
Copyright © 2020-2023  润新知