Java solution - two queues


  • 0
    B

    The elements all always in one queue, another queue is used temporarily(it will be empty after any of the four API methods called). Only standard JAVA queue api was used(offer, poll, size, isEmpty).

    /* cur refers to Q containing all the elements */
    Queue<Integer> cur = new LinkedList<>();
    
    /* other used as tmp Q; always empty after API called */
    Queue<Integer> other = new LinkedList<>();
    
    private void swapQ(){
        Queue<Integer> tmp = cur;
        cur = other;
        other = tmp;
    }
    
    // Push element x onto stack.
    public void push(int x) {
        cur.offer(x);
    }
    
    // Removes the element on top of the stack.
    public void pop() {
        while(cur.size() > 1)
            other.offer(cur.poll());
        cur.poll();
        swapQ();
    }
    
    // Get the top element.
    public int top() {
        while(cur.size() > 1)
            other.offer(cur.poll());
        int res = cur.poll();
        other.offer(res);
        swapQ();
        return res;
    }
    
    // Return whether the stack is empty.
    public boolean empty() {
        return cur.isEmpty();
    }

  • 0
    H
    This post is deleted!

  • 0
    B
    This post is deleted!

Log in to reply
 

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