Wednesday, December 2, 2015

Queue Implementation using Two Stacks

import java.util.Stack;

public class Queue {
    Stack<Integer> S1;
    Stack<Integer> S2;
    public Queue() {
        S1 = new Stack<Integer>();
        S2 = new Stack<Integer>();
    }
    public void enqueue(int data)    {
        S1.push(data);
    }
    private void ShiftS1toS2()    {
        while(!S1.isEmpty())
            S2.push(S1.pop());
    }
    public int dequeue()    {
        ShiftS1toS2();
        return S2.pop();
    }
    public int lookup()    {
        ShiftS1toS2();
        return S2.peek();
    }
}

No comments:

Post a Comment

UA-39217154-2