LeetCode 225:用隊列實現棧 Implement Stack using Queues

題目:

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

  • push(x) -- 元素 x 入棧
  • pop() -- 移除棧頂元素
  • top() -- 獲取棧頂元素
  • empty() -- 返回棧是否爲空

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

示例:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);  
stack.top();   // 返回 2
stack.pop();   // 返回 2
stack.empty(); // 返回 false

注意:

  • 你只能使用隊列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 這些操作是合法的。
  • 你所使用的語言也許不支持隊列。 你可以使用 list 或者 deque(雙端隊列)來模擬一個隊列 , 只要是標準的隊列操作即可。
  • 你可以假設所有操作都是有效的(例如, 對一個空的棧不會調用 pop 或者 top 操作)

Notes:

  • You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

解題思路:

方法一(兩個隊列):

​ 隊列先進後出,棧後進先出。用隊列實現棧,可以用兩個隊列完成題解:

​ 出入棧:

​ 入棧時用 queue1 來存入節點;出棧時queue1 內節點順序出隊列併入隊列到 queue2,直到queue1剩最後一個元素時即爲棧頂元素,彈出即可;

​ 取棧頂元素:

​ 用一個 top 指針一直指向棧頂元素,top() 方法查詢棧頂元素時直接返回 top 指針即可。

方法二(一個隊列):

​ 只用一個隊列,只需要在入棧時反轉隊列即可:

入棧存入到隊列queue

節點1入棧:queue:1
反轉隊列0次:queue:1

節點2入棧queue:1->2
反轉隊列1次:
queue:1->2 --> queue:2->1

節點2入棧queue:2->1->3
反轉隊列2次:
queue:2->1->3 ---> queue:1->3->2 ---> queue:3->2->1

......

這樣不管什麼時候出隊順序都是按照出棧的順序。

Java:

方法一

class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;
    private int top;//指向棧頂元素

    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        queue1.offer(x);
        top = x;//新加入元素爲棧頂元素
    }

    public int pop() {
        while (queue1.size() > 1) {//條件爲隊列1的元素個數大於一
            top = queue1.poll();//用top暫存元素,當循環結束時,top剛好是棧頂元素
            queue2.add(top);
        }
        //隊列1與隊列2交換
        Queue<Integer> tmp = queue2;
        queue2 = queue1;
        queue1 = tmp;
        return queue2.poll();//返回隊列2的隊列頭元素,隊列2也只有一個元素
    }

    public int top() {
        return top;
    }

    public boolean empty() {
        return queue1.isEmpty();//隊列1決定了棧是否爲空
    }
}

方法二:

每次入隊時反轉隊列即可,只有入棧需要特殊操作,出棧、取棧頂元素、是否空都按照隊列正常出隊列、取隊列頭元素、是否空方法操作。下面是入棧時代碼:

Queue<Integer> queue = new LinkedList<>();

public void push(int x) {
    queue.add(x);
    int sz = queue.size();//獲得隊列長度
    while (sz > 1) {//反轉次數爲隊列長度減一
        queue.add(queue.remove());//反轉
        sz--;
    }
}

Python:

Python語言沒有棧和隊列數據結構,只能用數組 List 或雙端隊列 deque 實現。

這類編程語言就壓根不需要 用隊列實現棧或用棧實現隊列這種問題,因爲棧和隊列本身就必須藉助List、deque實現。

所以這道題在這種語言中這就非常簡單了,可以說是作弊。

class MyStack:

    def __init__(self):
        self.stack = []

    def push(self, x: int) -> None:
        self.stack.append(x)

    def pop(self) -> int:
        return self.stack.pop(-1)

    def top(self) -> int:
        return self.stack[-1]

    def empty(self) -> bool:
        return not self.stack

歡迎關注微.信公.衆號:愛寫Bug

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章