fork(1) download
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3. /**
  4.  * Interface declaring the operations supported by a Stack
  5.  * @author Prateek
  6.  *
  7.  * @param <T> : Type to the Elements to be inserted into Stack
  8.  */
  9. interface IStack<T> {
  10. void push(T item);
  11. T pop();
  12. T peek();
  13. boolean isEmpty();
  14. }
  15.  
  16. /**
  17.  * Implement Stack using Queues
  18.  * @author Prateek
  19.  */
  20. class StackwithQueues implements IStack<Integer> {
  21.  
  22. //for pushing data
  23. private Queue<Integer> queue1 = new LinkedList<Integer>();
  24.  
  25. // used for reversing the data of queue1 and flipping of queues
  26. private Queue<Integer> queue2 = new LinkedList<Integer>();
  27.  
  28. /**
  29. * Push operation of Stack
  30. * Item pushed into Queue1
  31. */
  32. @Override
  33. public void push(Integer item) {
  34. System.out.println("Push : "+item);
  35. queue1.offer(item);
  36. }
  37.  
  38. /**
  39. * Pop operation of Stack
  40. * last item of queue1 is returned,
  41. * order is reversed using queue2
  42. */
  43. @Override
  44. public Integer pop() {
  45. Integer item=null;
  46. if(!queue1.isEmpty())
  47. {
  48. while (!queue1.isEmpty())
  49. {
  50. item=queue1.poll();
  51. if(!queue1.isEmpty())
  52. queue2.add(item);
  53. }
  54. flip();
  55. }
  56. else
  57. System.out.println("Stack is Empty");
  58. System.out.println("Poped : "+ item);
  59. return item;
  60. }
  61.  
  62. /**
  63. * Peek operation, similar to pop ,
  64. * with slight modification
  65. */
  66. @Override
  67. public Integer peek() {
  68. Integer item=null;
  69. while (!queue1.isEmpty()) {
  70. item=queue1.poll();
  71. queue2.add(item);
  72. }
  73. flip();
  74. System.out.println("Peek : "+ item);
  75. return item;
  76. }
  77.  
  78. @Override
  79. public boolean isEmpty() {
  80. return queue1.isEmpty();
  81. }
  82.  
  83. /**
  84. * Flipping of Queues
  85. */
  86. public void flip(){
  87. Queue<Integer> tQueue= queue1;
  88. queue1=queue2;
  89. queue2 = tQueue;
  90. }
  91.  
  92. public static void main(String[] args) {
  93. StackwithQueues obj=new StackwithQueues();
  94. obj.push(1);
  95. obj.push(2);
  96. obj.push(3);
  97. obj.push(4);
  98. obj.peek();
  99. obj.pop();
  100. obj.pop();
  101. obj.peek();
  102. obj.pop();
  103. obj.pop();
  104. obj.pop();
  105.  
  106. }
  107.  
  108. }
  109.  
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
Push : 1
Push : 2
Push : 3
Push : 4
Peek : 4
Poped : 4
Poped : 3
Peek : 2
Poped : 2
Poped : 1
Stack is Empty
Poped : null