Wednesday 30 May 2012

How to construct a queue data structure using stacks


Stacks and queues.

  
Each is defined by two basic operations: insert a new item, and remove an item. When we insert an item, our intent is clear. But when we remove an item, which one do we choose? The rule used for a queue is to always remove the item that has been in the collection the mostamount of time. This policy is known as first-in-first-out or FIFO. The rule used for a stack is to always remove the item that has been in the collection the least amount of time. This policy is known as last-in first-out or LIFO.


construct a queue data structure using only the Single stacks


public class SimulatedQueue<E> { 
    private java.util.Stack<E> stack = new java.util.Stack<E>(); 

    public void insert(E elem) { 
        if (!stack.empty()) { 
            E topElem = stack.pop(); 
            insert(elem); 
            stack.push(topElem); 
        } 
        else 
            stack.push(elem); 
    } 

    public E remove() { 
        return stack.pop(); 
    } 
}


construct a queue data structure using only the two stacks


public class Queue<E> 


    private Stack<E> inbox = new Stack<E>(); 
    private Stack<E> outbox = new Stack<E>(); 

    public void queue(E item) { 
        inbox.push(item); 
    } 

    public E dequeue() { 
        if (outbox.isEmpty()) { 
            while (!inbox.isEmpty()) { 
               outbox.push(inbox.pop()); 
            } 
        } 
        return outbox.pop(); 
    } 

}

No comments:

Post a Comment