天天看點

leetcode225-用隊列實作棧

  • ​​用隊列實作棧​​
  • ​​題目描述​​
  • ​​code​​

用隊列實作棧

題目描述

code

class MyStack {
        //使用兩個隊列, 先将元素添加到一個棧中,然後再将元素倒入另一個棧中,這樣順序就還原正常
        private Queue<Integer> a = new LinkedList<>();
        private Queue<Integer> b = new LinkedList<>();

        /** Initialize your data structure here. */
        public MyStack() {

        }

        /** Push element x onto stack. */
        /**
         * 通過總結: 有循環向兩個容器交換資料的邏輯,是以可以交換兩個容器的指向,這樣效率更高,聰明
         * @param x
         */
        public void push(int x) {
            a.offer(x);
            // 将b隊列中元素全部轉給a隊列
            while(!b.isEmpty())
                a.offer(b.poll());
            // 交換a和b,使得a隊列沒有在push()的時候始終為空隊列
            Queue temp = a;
            a = b;
            b = temp;
        }

        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            return b.poll();
        }

        /** Get the top element. */
        public int top() {
            return b.peek();
        }

        /** Returns whether the stack is empty. */
        public boolean empty() {
            return b.isEmpty();
        }
    }