2026/05/11

[LeetCode] 225 Implement Stack using Queues

用queue模擬stack

每次push時, 先push當前element, 再把所有element從新pop出來 + push進去

 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
class MyStack {
private:
  std::queue<int> Q;

public:
  MyStack() {}
  void push(int x) {
    Q.push(x);
    int N = Q.size() - 1;
    for (int i = 0; i < N; i++) {
      Q.push(Q.front());
      Q.pop();
    }
  }

  int pop() {
    int ret = Q.front();
    Q.pop();
    return ret;
  }

  int top() { return Q.front(); }

  bool empty() { return Q.empty(); }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */