Post

Implement Queue using Stacks

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class MyQueue {

    private Deque<Integer> stackOne;
    private Deque<Integer> stackTwo;

    public MyQueue() {
        stackOne = new LinkedList<>();
        stackTwo = new LinkedList<>();
    }
    
    public void push(int x) {
        stackOne.push(x);
    }
    
    public int pop() {
        if (stackTwo.isEmpty()) {
            transferStack();
        }
        return stackTwo.pop();
    }
    
    public int peek() {
        if (stackTwo.isEmpty()) {
            transferStack();
        }
        return stackTwo.peek();
    }
    
    public boolean empty() {
        return stackOne.isEmpty() && stackTwo.isEmpty();
    }

    private void transferStack() {
        while (!stackOne.isEmpty()) {
            stackTwo.push(stackOne.pop());
        }
    }
}

/**
 * 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();
 */

Complexity

  • Time = O(k),k 为 n 的二进制长度
  • Space = O(1)

This post is licensed under CC BY 4.0 by the author.