Accepted Java two queue solution


  • 0
    M
    class MyStack {
    
    private Queue<Integer> []queue;
    private int currQueue = 0;
    
    public MyStack(){
        queue = new LinkedList[2];
        queue[0] = new LinkedList();
        queue[1] = new LinkedList();
    }
    // Push element x onto stack.
    public void push(int x) {
        queue[currQueue].add(x);
    }
    
    // Removes the element on top of the stack.
    public void pop() {
        int size = queue[currQueue].size();
        while(size-- > 1)
            queue[currQueue ^ 1].add(queue[currQueue].poll());
        queue[currQueue].poll();
        currQueue ^= 1;
    }
    
    // Get the top element.
    public int top() {
        int size = queue[currQueue].size();
        while(size-- > 1)
            queue[currQueue ^ 1].add(queue[currQueue].poll());
        return queue[currQueue].peek();
    }
    
    // Return whether the stack is empty.
    public boolean empty() {
        return queue[currQueue].isEmpty() && queue[currQueue ^ 1].isEmpty();
    }
    

    }


Log in to reply
 

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