1. 程式人生 > 其它 >LeetCode 232. Implement Queue using Stacks

LeetCode 232. Implement Queue using Stacks

LeetCode 232. Implement Queue using Stacks (用棧實現佇列)

題目

連結

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

問題描述

請你僅使用兩個棧實現先入先出佇列。佇列應當支援一般佇列支援的所有操作(push、pop、peek、empty):

實現 MyQueue 類:

void push(int x) 將元素 x 推到佇列的末尾
int pop() 從佇列的開頭移除並返回元素
int peek() 返回佇列開頭的元素
boolean empty() 如果佇列為空,返回 true ;否則,返回 false
說明:

你 只能 使用標準的棧操作 —— 也就是隻有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的語言也許不支援棧。你可以使用 list 或者 deque(雙端佇列)來模擬一個棧,只要是標準的棧操作即可。

1 <= x <= 9
最多呼叫 100 次 push、pop、peek 和 empty
假設所有操作都是有效的 (例如,一個空的佇列不會呼叫 pop 或者 peek 操作)

示例

輸入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
輸出:
[null, null, null, 1, 1, false]

解釋:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

提示

思路

複雜度分析

時間複雜度 O(n)
空間複雜度 O(n)

程式碼

Java

    private Stack<Integer> s1;
    private Stack<Integer> s2;

    public MyQueue() {
        s1 = new Stack<>();
        s2 = new Stack<>();
    }

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


    public int pop() {
        if (s2.isEmpty()) {
            while (!s1.isEmpty()) {
                s2.push(s1.pop());
            }
        }
        return s2.pop();
    }

    public int peek() {
        if (s2.isEmpty()) {
            while (!s1.isEmpty()) {
                s2.push(s1.pop());
            }
        }
        return s2.peek();
    }

    public boolean empty() {
        if (s1.isEmpty() && s2.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }