zoukankan      html  css  js  c++  java
  • 225. 用队列实现栈

    传送门

    代码

    class MyStack {
        Queue<Integer> que1;
        Queue<Integer> que2;
        /** Initialize your data structure here. */
        public MyStack() {
            que1 = new LinkedList<>();
            que2 = new LinkedList<>();
        }
        
        /** Push element x onto stack. */
        public void push(int x) {
            que1.offer(x);
        }
        
        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            int size = que1.size();
            for(int i = 0;i < size - 1; ++i) {
                que2.offer(que1.poll());
            }
            int val = que1.poll();
            while(!que2.isEmpty()) {
                que1.offer(que2.poll());
            }
            return val;
        }
        
        /** Get the top element. */
        public int top() {
            int _top;
            int size = que1.size();
            for(int i = 0;i < size - 1; ++i) {
                que2.offer(que1.poll());
            }
            _top = que1.poll();
            que2.offer(_top);
            while(!que2.isEmpty()) {
                que1.offer(que2.poll());
            }
            return _top;
        }
        
        /** Returns whether the stack is empty. */
        public boolean empty() {
            return que1.isEmpty();
        }
    }
    

    思路

    用两个队列实现一个栈

    (que1) 当主队列,(que2) 当辅助队列

    添加元素都往(que1) 上添加,

    删除元素或者,查看栈顶元素的时候,就把(que1) 全部倒出来,先暂放到 (que2) 中,最后在倒回去(que1) 中即可

  • 相关阅读:
    HDU 5091 Beam Cannon (扫描线思想)
    UVA12904 Load Balancing(中途相遇法)
    linux虚拟机时间同步
    linux shell
    项目bug
    定时发送邮件出现问题
    kafka里面的topic消费情况查看
    kafka常见命令
    HiJson简要说明
    zookeeper、hbase常见命令
  • 原文地址:https://www.cnblogs.com/lukelmouse/p/14220712.html
Copyright © 2011-2022 走看看