import java.util.Stack;
/**
* Implement Queue operations using two stacks
* @author Prateek
*/
class QueueQWithStacks {
private Stack<Integer> stack1 = new Stack<Integer>(); // for enqeue operations
private Stack<Integer> stack2 = new Stack<Integer>();
/**
* Enqueue Operation
* @throws InterruptedException : to given delay between operations so that it prints on console
*/
System.
out.
println("Enqueue: " + item
); stack1.push(item);
}
/**
* Dequeue Operation
* @return FIFO element
*/
if(stack2.isEmpty())
{
if(!stack1.isEmpty())
{
while(!stack1.isEmpty())
{
stack2.push(stack1.pop());
}
}
else
{
System.
out.
println("Stack is Empty"); return -1;
}
}
int item=stack2.pop();
System.
out.
println("Dequeue: " + item
); return item;
}
QueueQWithStacks obj=new QueueQWithStacks();
obj.enqueue(1);
obj.enqueue(2);
obj.enqueue(3);
obj.dequeue();
obj.dequeue();
obj.dequeue();
obj.dequeue();
obj.enqueue(4);
obj.enqueue(5);
obj.enqueue(6);
obj.enqueue(7);
obj.dequeue();
obj.dequeue();
obj.dequeue();
obj.dequeue();
obj.dequeue();
}
}
aW1wb3J0IGphdmEudXRpbC5TdGFjazsKLyoqCiAqIEltcGxlbWVudCBRdWV1ZSBvcGVyYXRpb25zIHVzaW5nIHR3byBzdGFja3MKICogQGF1dGhvciBQcmF0ZWVrCiAqLwogY2xhc3MgUXVldWVRV2l0aFN0YWNrcyAgewoKCXByaXZhdGUgU3RhY2s8SW50ZWdlcj4gc3RhY2sxID0gbmV3IFN0YWNrPEludGVnZXI+KCk7IC8vIGZvciBlbnFldWUgb3BlcmF0aW9ucwoJcHJpdmF0ZSBTdGFjazxJbnRlZ2VyPiBzdGFjazIgPSBuZXcgU3RhY2s8SW50ZWdlcj4oKTsKCgkvKioKCSAqIEVucXVldWUgT3BlcmF0aW9uCgkgKiBAdGhyb3dzIEludGVycnVwdGVkRXhjZXB0aW9uIDogdG8gZ2l2ZW4gZGVsYXkgYmV0d2VlbiBvcGVyYXRpb25zIHNvIHRoYXQgaXQgcHJpbnRzIG9uIGNvbnNvbGUKCSAqLwoJ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