fork download
  1. import java.util.Arrays;
  2. /**
  3.  * Queue Interface that ADT supports
  4.  * @author Prateek
  5.  * @param <T>
  6.  */
  7. interface IQueue<T> {
  8. /**
  9. * Inserts an item to Queue, pointed by Rear.
  10. * @param item
  11. */
  12. void enqueue(T item);
  13.  
  14. /**
  15. * @return oldest element in the queue, pointer by front pointer
  16. */
  17. T dequeue();
  18.  
  19. boolean isEmpty();
  20.  
  21. /*return size of Queue*/
  22. int size();
  23.  
  24. boolean isFull();
  25. }
  26.  
  27. /**
  28.  * Circular Queue
  29.  * @author Prateek....
  30.  */
  31. class CircularQueue implements IQueue<Integer>{
  32.  
  33. private static final int DEFAULT_CAPACITY = 5;
  34. private int N,front,rear;
  35. private int[] arr;
  36.  
  37. public CircularQueue() {
  38. arr = new int[DEFAULT_CAPACITY];
  39. N=DEFAULT_CAPACITY;
  40. Arrays.fill(arr, -1);
  41. front = rear =0;
  42. }
  43.  
  44. public CircularQueue(int capacity){
  45. arr = new int[capacity];
  46. N=DEFAULT_CAPACITY;
  47. Arrays.fill(arr, -1);
  48. front = rear =0;
  49. }
  50.  
  51. @Override
  52. public void enqueue(Integer item) {
  53. if(isFull())
  54. System.err.println("Stack is Full");
  55. else {
  56. arr[rear] = item;
  57. rear = (rear +1 ) % N;
  58. }
  59. }
  60.  
  61. @Override
  62. public Integer dequeue() {
  63. if(isEmpty()){
  64. System.err.println("Stack is Empty");
  65. return null;
  66. }
  67. else{
  68. int val=arr[front];
  69. arr[front] = -1;
  70. front = (front +1) % N ;
  71. return val;
  72. }
  73. }
  74.  
  75. @Override
  76. public boolean isEmpty() {
  77. return (front == rear) ? true : false;
  78. }
  79.  
  80. @Override
  81. public boolean isFull() {
  82. int diff = rear - front;
  83. return (diff == N-1 || diff == -1) ? true : false;
  84. }
  85.  
  86. @Override
  87. public int size() {
  88. return (rear > front) ? (rear-front) : (N - (front - rear));
  89. }
  90.  
  91. /**
  92. * Displays the content of the Queue
  93. */
  94. public void display(){
  95. int size = size();
  96. int index = front;
  97. int count=0;
  98.  
  99. while(count!=size){
  100. System.out.print(arr[index]+"\t");
  101. index = (index + 1) % N;
  102. count++;
  103. }
  104. }
  105.  
  106. public static void main(String[] args) {
  107. CircularQueue queue = new CircularQueue();
  108. queue.enqueue(1);
  109. queue.enqueue(2);
  110. queue.enqueue(3);
  111. queue.enqueue(4);
  112. queue.enqueue(5);
  113. queue.enqueue(6);
  114. queue.dequeue();
  115. queue.dequeue();
  116. queue.enqueue(7);
  117. queue.display();
  118.  
  119. }
  120. }
  121.  
Success #stdin #stdout #stderr 0.07s 380160KB
stdin
Standard input is empty
stdout
3	4	7	
stderr
Stack is Full
Stack is Full