fork download
  1. import java.util.Stack;
  2. /**
  3.  * Implement Queue operations using two stacks
  4.  * @author Prateek
  5.  */
  6. class QueueQWithStacks {
  7.  
  8. private Stack<Integer> stack1 = new Stack<Integer>(); // for enqeue operations
  9. private Stack<Integer> stack2 = new Stack<Integer>();
  10.  
  11. /**
  12. * Enqueue Operation
  13. * @throws InterruptedException : to given delay between operations so that it prints on console
  14. */
  15. public void enqueue(Integer item) throws InterruptedException {
  16. Thread.sleep(10);
  17. System.out.println("Enqueue: " + item);
  18. stack1.push(item);
  19. }
  20.  
  21. /**
  22. * Dequeue Operation
  23. * @return FIFO element
  24. */
  25. public Integer dequeue() throws InterruptedException {
  26. Thread.sleep(10);
  27. if(stack2.isEmpty())
  28. {
  29. if(!stack1.isEmpty())
  30. {
  31. while(!stack1.isEmpty())
  32. {
  33. stack2.push(stack1.pop());
  34. }
  35. }
  36. else
  37. {
  38. System.out.println("Stack is Empty");
  39. return -1;
  40. }
  41. }
  42. int item=stack2.pop();
  43. System.out.println("Dequeue: " + item);
  44. return item;
  45. }
  46.  
  47. public static void main(String[] args) throws InterruptedException {
  48. QueueQWithStacks obj=new QueueQWithStacks();
  49. obj.enqueue(1);
  50. obj.enqueue(2);
  51. obj.enqueue(3);
  52. obj.dequeue();
  53. obj.dequeue();
  54. obj.dequeue();
  55. obj.dequeue();
  56. obj.enqueue(4);
  57. obj.enqueue(5);
  58. obj.enqueue(6);
  59. obj.enqueue(7);
  60. obj.dequeue();
  61. obj.dequeue();
  62. obj.dequeue();
  63. obj.dequeue();
  64. obj.dequeue();
  65. }
  66. }
  67.  
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
Enqueue: 1
Enqueue: 2
Enqueue: 3
Dequeue: 1
Dequeue: 2
Dequeue: 3
Stack is Empty
Enqueue: 4
Enqueue: 5
Enqueue: 6
Enqueue: 7
Dequeue: 4
Dequeue: 5
Dequeue: 6
Dequeue: 7
Stack is Empty