Java Solution; O(n) pop running time, O(n) memory; 93ms.


  • 0
    S
    class MyStack {
      private Queue<Integer> q = new ArrayDeque<>();
      private Queue<Integer> p = new ArrayDeque<>();
    
      public void push(int x) {
        q.add(x);
      }
    
      public void pop() {
        copy();
        q.poll();
        swap();
      }
    
      public int top() {
        copy();
        final int value = q.poll();
        p.add(value);
        swap();
        return value;
      }
    
      public boolean empty() {
        return q.isEmpty();
      }
    
      private void copy() {
        for (int i = 0, s = q.size() - 1; i < s; i++) {
          p.add(q.poll());
        }
      }
    
      private void swap() {
        final Queue<Integer> temp = q;
        q = p;
        p = temp;
      }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.