[Leetcode in Java] 232. Implement Queue using Stacks


Posted by LarsonKao on 2022-05-10

232. Implement Queue using Stacks

Link

難易度 : Easy

question

題目要求只能使操作stack來實作queue的功能,相信stack跟queue應該都知道是什麼東西
最基本的觀念就是

stack : 先進後出(FILO)
queue : 先進先出(FIFO)

那麼想要使用stack來達到queue的效果可以怎麼做呢?
這邊我選擇使用2個stack

  1. stackIn : 專門處理push操作
  2. stackOut : 專門處理pop與peek操作

實際的思路是

  1. push時直接放進stackIn中
  2. pop或peek時使用stackOut來pop,若stackOut中沒東西了,就一股腦將stackIn的東西全部都到stackOut來
  3. 千萬不能push一個丟一個過去,這樣就等同使用一個Stack了沒有任何意義
    class MyQueue {
        Stack<Integer> stackIn;
        Stack<Integer> stackOut;

        public MyQueue() {
            stackIn = new Stack<Integer>();
            stackOut = new Stack<Integer>();
        }

        public void push(int x) {
            stackIn.push(x);
        }

        public int pop() {
            EmptyStackIn();
            return stackOut.pop();
        }

        public int peek() {
            EmptyStackIn();
            int value = stackOut.pop();
            stackOut.push(value);
            return value;
        }

        public boolean empty() {
            return stackIn.isEmpty()&&stackOut.isEmpty();
        }

        private void EmptyStackIn() 
        {
            if(stackOut.isEmpty()) 
            {
                while(!stackIn.isEmpty()) 
                {
                    stackOut.push(stackIn.pop());
                }
            }
        }
    }

result

睡到半夜忽然一個發燒,嚇得我趕緊跟公司請假在家好好休養(寫code)QQ


#Leetcode #java #algorithm #stack #Queue







Related Posts

關於 CSS 最 Confusing 的位置以及顯示方式

關於 CSS 最 Confusing 的位置以及顯示方式

[ MTR04 ] W4_NET101_ 由上到下:從 HTTP 協定開始講起

[ MTR04 ] W4_NET101_ 由上到下:從 HTTP 協定開始講起

SQL 筆記

SQL 筆記


Comments