Implement Stack using Queues

Implement the following operations of a stack using queues.

class MyStack {
    // Push element x onto stack.
    // Use LinkedList to initialize Queue in Java 
    private Queue<Integer> q1 = new LinkedList<>();  
    private Queue<Integer> q2 = new LinkedList<>(); 
    
    
    public void push(int x) {
        q1.offer(x);
    }

    // Removes the element on top of the stack.
    public void pop() { 
        while (q1.size() > 1) {
            q2.offer(q1.poll());
        }
        q1.poll(); 
        
        Queue<Integer> temp; 
        temp = q2;
        q2 = q1; 
        q1 = temp; 
    }

    // Get the top element.
    public int top() {
        while (q1.size() > 1) {
            q2.offer(q1.poll()); 
        }
        int top  = q1.peek();
        q2.offer(q1.poll()); 
        
        Queue<Integer> temp; 
        temp = q2; 
        q2 = q1; 
        q1 = temp; 
        
        return top; 
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return (q1.size() == 0);
    }
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s