Two queue java solution


  • 2
    C
    class MyStack {
        Queue<Integer> q = new LinkedList<>();
        Queue<Integer> tmp = new LinkedList<>();
        // Push element x onto stack.
        public void push(int x) {
            //pop elements in q into tmp
            while(!q.isEmpty()){
                tmp.offer(q.poll());
            }
            //add x into q
            q.offer(x);
            //pop elements in tmp into q
            while(!tmp.isEmpty()){
                q.offer(tmp.poll());
            }
        }
    
        // Removes the element on top of the stack.
        public void pop() {
            q.poll();
        }
    
        // Get the top element.
        public int top() {
            return q.peek();
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
            return q.isEmpty();
        }
    }

  • 0
    H

    I don't understand. In push(), if you can use one loop to push the last element to front, why bother to use extra Queue?


Log in to reply
 

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