zoukankan      html  css  js  c++  java
  • 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();
            }
        }
        

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

  • 相关阅读:
    考虑浏览器兼容的文件上传(IE8不支持FormData)
    IDEA tomcat 部署WEB项目
    如何在springcloud分布式系统中实现分布式锁?
    ABAP DEMO33 选择周的搜索帮助
    ABAP函数篇1 日期函数
    ABAP函数篇2 测试DATE_CONVERT_TO_FACTORYDATE
    增强篇7 判断标准屏幕能否做屏幕增强
    增强篇6 CMOD增强删除
    ABAP DEMO 年月的搜索帮助
    HoloLens开发手记-配置开发环境 Install the tools
  • 原文地址:https://www.cnblogs.com/zhangfanxmian/p/6929922.html
Copyright © 2011-2022 走看看