public class QueueWithTwoStack<Item>
{
Stack<Item> s1=new Stack<Item>();
Stack<Item> s2=new Stack<Item>();
public boolean isEmpty()
{
return s1.isEmpty() && s2.isEmpty();
}
public int size()
{
return s1.size()+s2.size();
}
public void enqueue(Item item)
{
s1.push(item);
}
public Item dequeue()
{
if(s2.isEmpty())
{
while(!s1.isEmpty())
s2.push(s1.pop());
}
//
return s2.pop();
}
public static void main(String[] args)
{
QueueWithTwoStack<String> q=new QueueWithTwoStack<String>();
q.enqueue("1");
q.enqueue("2");
q.enqueue("3");
//
StdOut.print(q.dequeue()+ " ");
//
q.enqueue("4");
StdOut.print(q.dequeue()+ " ");
//
q.enqueue("5");
q.enqueue("6");
//
while(!q.isEmpty())
StdOut.print(q.dequeue()+ " ");
}
}