天天看點

leetcode 232. 用棧實作隊列(詳細分析)

連結:https://leetcode-cn.com/problems/implement-queue-using-stacks

使用棧實作隊列的下列操作:

push(x) – 将一個元素放入隊列的尾部。

pop() – 從隊列首部移除元素。

peek() – 傳回隊列首部的元素。

empty() – 傳回隊列是否為空。

示例:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // 傳回 1
queue.pop();   // 傳回 1
queue.empty(); // 傳回 false
           

說明:

1.你隻能使用标準的棧操作 – 也就是隻有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。

2.你所使用的語言也許不支援棧。你可以使用 list 或者 deque(雙端隊列)來模拟一個棧,隻要是标準的棧操作即可。

3.假設所有操作都是有效的 (例如,一個空的隊列不會調用 pop 或者 peek 操作)。

JAVA

思路

(1).入隊列: 将元素放入s1中;

(2).出隊列: 檢測s2是否為空:

①.為空:将s1中的元素搬到s2中,删除s2中的棧頂元素,出隊列。

②.非空: 直接删除s2棧頂元素,出隊列。

(3).擷取隊列首部元素:檢測s2是否為空:

①.為空:将s1中的元素搬移到s2,從s2棧頂擷取。

②.非空:從s2棧頂直接擷取。

(4).隊列是否為空:s1、s2兩個棧都為空,即隊列為空。

代碼如下:

class MyQueue{
      private Stack<Integer> s1;
      private 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() {
         if (s2.empty()) { //如果s2為空,就把s1中的元素全部移到s2中
            while (!s1.empty()) { //s1不為空:裡面還有元素
                s2.push(s1.pop());//s1中的元素移入s2
            }
        }
        return s2.pop();
    }
    
    /** Get the front element. */
    public int peek() {
         if (s2.empty()) {
            while (!s1.empty()) { //s1不為空:裡面還有元素
                s2.push(s1.pop());//s1中的元素移入s2
            }
        }
        return s2.peek();//擷取棧頂元素
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
         return s1.empty() && s2.empty();
    }
}

           

繼續閱讀