Stories

Detail Return Return

算法 - 棧與隊列 - 用棧組成隊列 - Stories Detail

力扣 232題 用棧實現隊列

請你僅使用兩個棧實現先入先出隊列。隊列應當支持一般隊列支持的所有操作(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:

輸入:
["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

來源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/implement-queue-using-stacks
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

解法:兩個棧,一個用於存進入的數據,另一個存要出去的數據

class MyQueue {

    Stack<Integer> stack1 = new Stack();
    Stack<Integer> stack2 = new Stack();

    public MyQueue() {
    }

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

    public int pop() {
        if(stack2.isEmpty()){
            in2out();
        }
        return stack2.pop();
    }

    public int peek() {
        if(stack2.isEmpty()){
            in2out();
        }
        return stack2.peek();
    }

    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }

    private void in2out() {
        while (!stack1.isEmpty()) {
            stack2.push(stack1.pop());
        }
    }
}

Add a new Comments

Some HTML is okay.