Friday, 29 June 2012

Stack implementation in java using Queue

This is the one of the most frequently asked question in core-java interviews.

I would recommend you to look previous posts in my blog about "Stack implementation" and "Queue implementation" so that, it would make more sense to understand below code.


 1. StackImplUsingQueue.java


package ora.stackex;

import ora.queue.Queue;
import ora.queue.QueueImpl;

public class StackImplUsingQueue implements Stack {
   
    private Queue queue;
   
    @Override
    public boolean isEmpty() {
        return queue == null ? true : (queue.size() == 0);
    }

    @Override
    public Object pop() throws StackEmptyException {
        if (isEmpty())
            return null;
       
        for (int i=0; i<size()-1; i++)
            queue.enqueue(queue.dequeue());
        return queue.dequeue();
    }

    @Override
    public void push(Object obj) throws StackOverflowException {
        if (isEmpty())
            queue = new QueueImpl();
        queue.enqueue(obj);
    }

    @Override
    public int size() {
        return queue == null ? 0 : queue.size();
    }

    @Override
    public Object top() throws StackEmptyException {
        if (isEmpty())
            return null;
       
        Object obj = pop();
        queue.enqueue(obj);
        return obj;
    }

}


No comments:

Post a Comment