1. 程式人生 > 實用技巧 >Leetcode232.用堆疊實現佇列

Leetcode232.用堆疊實現佇列

使用棧實現佇列的下列操作:

push(x) -- 將一個元素放入佇列的尾部。
pop() -- 從佇列首部移除元素。
peek() -- 返回佇列首部的元素。
empty() -- 返回佇列是否為空。

連結:https://leetcode-cn.com/problems/implement-queue-using-stacks
思路:入棧的時候 還是正常入棧,出棧的時候將所有的輸入棧裡面的東西輸出 壓到輸出棧裡面,然後再輸出

class MyQueue {
    Stack<Integer> S1;
    Stack<Integer> S2;

    /** Initialize your data structure here. 
*/ public MyQueue() { S1=new Stack<>(); S2=new Stack<>(); } /** Push element x to the back of queue. */ public void push(int x) { S1.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() {
while(S2.isEmpty())//如果輸出棧為空 { while(!S1.isEmpty()) { S2.push(S1.pop()); //把輸入棧的全部放入輸出棧 } } return S2.pop(); } /** Get the front element. */ public int peek() { while(S2.isEmpty())//如果輸出棧為空
{ while(!S1.isEmpty()) { S2.push(S1.pop()); //把輸入棧的全部放入輸出棧 } } return S2.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return S1.isEmpty() && S2.isEmpty(); } } /** * 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(); */