leetcode 232兩個棧模擬一個佇列
阿新 • • 發佈:2018-12-31
原題:
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty
題意:用兩個棧實現一個佇列,需要完成的方法有1 入隊;2 出隊;3 獲取隊頭元素;4 判斷佇列是否為空。
思路其實蠻簡單的。難點主要是在使用棧模擬入隊出隊的過程。棧的特點是後進先出,佇列的特點是先進先出。我們藉助兩個棧,一個棧用於儲存入隊的元素(棧1),另一個棧用於出隊操作(棧2)。出隊的時候先判斷棧2是否為空,如果為空,去棧1判斷,說明前面一直在入棧,沒有出棧的操作。這時候將棧1中的元素全部出棧,加到棧2中去。這時候,通過棧2的出棧操作,來模擬出隊操作。
程式碼如下:
import java.util.*; class MyQueue { /** Initialize your data structure here. */ public MyQueue() { } Stack<Integer> stack1 =new Stack(); Stack<Integer> stack2 =new Stack();//題目中要求了,佇列中元素為int型 /** Push element x to the back of queue. */ public void push(int x) { stack1.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { if (stack2.isEmpty()){ while (!stack1.isEmpty()){ stack2.push(stack1.pop()); } } return stack2.pop(); } /** Get the front element. */ public int peek() { if (stack2.isEmpty()){ while (!stack1.isEmpty()){ stack2.push(stack1.pop()); } } return stack2.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { if(stack1.isEmpty()){ return stack2.isEmpty(); } if(stack2.isEmpty()){ return stack1.isEmpty(); }else{ return false; } } } /** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */