Anupznk

circular array

Apr 17th, 2021
49
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class MyQueueCircularArr {
  2. private static final int DEFAULT_SIZE = 1000;
  3. char[] arr;
  4. int head, tail, length, sizeOfArray;
  5.  
  6. public MyQueueCircularArr() {
  7. arr = new char[DEFAULT_SIZE];
  8. head = tail = length = 0;
  9. sizeOfArray = DEFAULT_SIZE;
  10. }
  11.  
  12. public MyQueueCircularArr(int size) {
  13. arr = new char[size];
  14. head = tail = length = 0;
  15. sizeOfArray = size;
  16. }
  17.  
  18. public void enqueue(char item) {
  19. if (tail < sizeOfArray) {
  20. arr[tail++] = item;
  21. length++;
  22. } else if (tail == sizeOfArray && tail != head) {
  23. tail = 0;
  24. if (tail == head) {
  25. System.out.println("The array is full");
  26. } else {
  27. arr[tail++] = item;
  28. length++;
  29. }
  30.  
  31. }
  32. }
  33.  
  34. public int dequeue() {
  35. length--;
  36. return arr[head++];
  37. }
  38.  
  39. public void printSequence() {
  40. int h = head;
  41. for (int i = 0; i < length; i++) {
  42. System.out.println(arr[h++] + " ");
  43. if (h == sizeOfArray)
  44. h = 0;
  45. }
  46. }
  47.  
  48. public char peek() throws Exception {
  49. if (!isEmpty()) {
  50. return arr[head];
  51. } else {
  52. throw new Exception("The queue is empty");
  53. }
  54. }
  55.  
  56. public void removeAnElement(char item) throws Exception {
  57. if (!isEmpty()) {
  58. if (arr[head] == item) {
  59. dequeue();
  60. } else {
  61. int h = head;
  62. for (int i = 0; i < length; i++, h++) {
  63. if (h == sizeOfArray)
  64. h = 0;
  65. if (arr[h] == item) {
  66. for (int j = h; j < length - 1; j++, h++) {
  67. if (h == sizeOfArray - 1)
  68. h = 0;
  69. arr[h] = arr[h + 1];
  70. }
  71. tail--;
  72. length--;
  73. break;
  74. }
  75. }
  76. }
  77.  
  78. } else {
  79. throw new Exception("The queue is empty");
  80. }
  81. }
  82.  
  83. public boolean isEmpty() {
  84. if (length == 0)
  85. return true;
  86. return false;
  87. }
  88. }
RAW Paste Data