Problem: 225. 用隊列實現棧
文章目錄
- 思路
- 復雜度
- Code
思路
👨?🏫 力扣官解
- 輔助隊列存棧頂元素
- 主隊列存逆序序列
復雜度
時間復雜度:
添加時間復雜度, 示例: O ( n ) O(n) O(n)
空間復雜度:
添加空間復雜度, 示例: O ( n ) O(n) O(n)
Code
class MyStack {Queue<Integer> q1;Queue<Integer> q2;public MyStack() {q1 = new LinkedList<Integer>();q2 = new LinkedList<Integer>();}public void push(int x) {q2.add(x);while(!q1.isEmpty()){q2.add(q1.poll());}Queue<Integer> tmp = q1;q1 = q2;q2 = tmp;}public int pop() {return q1.poll();}public int top() {return q1.peek();}public boolean empty() {return q1.size() == 0;}
}/*** 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();* boolean param_4 = obj.empty();*/