2026/05/10

[LeetCode] 232 Implement Queue using Stacks

用兩個stack模擬queue的FIFO行為

一個input stack負責push

一個output stack負責pop

要pop的時候, 把input倒過來推進去output

要怎麼做到amortized O(1)呢 ?

不是每次pop都要把全部元素pop+push一次

而是只要output stack空掉的時候再從input stack倒element出來即可

 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
class MyQueue {
private:
  std::stack<int> input;
  std::stack<int> output;

  // amortized O(1)
  void sync() {
    if (!output.empty())
      return;
    while (!input.empty()) {
      int tmp = input.top();
      output.push(tmp);
      input.pop();
    }
  }

public:
  MyQueue() {}

  void push(int x) { input.push(x); }

  int pop() {
    sync();
    int tmp = output.top();
    output.pop();
    return tmp;
  }

  int peek() {
    sync();
    return output.top();
  }

  bool empty() { return input.empty() && output.empty(); }
};

/**
 * 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();
 * bool param_4 = obj->empty();
 */