Day18 循环队列
1.循环队列在增加或者删除元素时头指针和尾指针都是当前位置+1,所以会出现假溢出的情况,要解决这个问题的话直接取模就可以;
2.这里为了区分空队列与满队列,留出了一个结点不放元素,则判空:head == tail,判满:head == (tail + 1) % TOTAL_SPACE;
1 /** 2 * Circle int queue. 3 * 4 */ 5 public class CircleIntQueue { 6 /** 7 * The total space. One space can never be used. 8 */ 9 public static final int TOTAL_SPACE = 10; 10 11 /** 12 * The data. 13 */ 14 int[] data; 15 16 /** 17 * The index for calculating the head. The actual head 18 * is head % TOTAL_SPACE. 19 */ 20 int head; 21 22 /** 23 * The index for calculating the tail. 24 */ 25 int tail; 26 27 /** 28 * The constructor 29 */ 30 public CircleIntQueue() { 31 data = new int[TOTAL_SPACE]; 32 head = 0; 33 tail = 0; 34 }// Of the first constructor 35 36 /** 37 * Enqueue. 38 * 39 * @param paraValue The value of the new node. 40 */ 41 public void enqueue(int paraValue) { 42 if ((tail + 1) % TOTAL_SPACE == head) { 43 System.out.println("Queue full."); 44 return; 45 } // Of if 46 47 data[tail % TOTAL_SPACE] = paraValue; 48 tail++; 49 }// Of enqueue 50 51 /** 52 * Dequeue. 53 * 54 * @return The value at the head. 55 */ 56 public int dequeue() { 57 if (head == tail) { 58 System.out.println("No element in the queue"); 59 return -1; 60 } // Of if 61 62 int resultValue = data[head % TOTAL_SPACE]; 63 64 head++; 65 66 return resultValue; 67 }// Of dequeue 68 69 /** 70 * Overrides the method claimed in Object, the superclass 71 * of any class. 72 */ 73 public String toString() { 74 String resultString = ""; 75 76 if (head == tail) { 77 return "empty"; 78 } // Of if 79 80 for (int i = head; i < tail; i++) { 81 resultString += data[i % TOTAL_SPACE] + ", "; 82 } // Of for i 83 84 return resultString; 85 }// Of toString 86 87 /** 88 * The entrance of the program. 89 * 90 * @param args Not used now. 91 */ 92 public static void main(String args[]) { 93 CircleIntQueue tempQueue = new CircleIntQueue(); 94 System.out.println("Initialized, the list is: " + tempQueue.toString()); 95 96 for (int i = 0; i < 5; i++) { 97 tempQueue.enqueue(i + 1); 98 } // Of for i 99 System.out.println("Enqueue, the queue is: " + tempQueue.toString()); 100 101 int tempValue = tempQueue.dequeue(); 102 System.out.println("Dequeue " + tempValue + ", the queue is: " + tempQueue.toString()); 103 104 for (int i = 0; i < 6; i++) { 105 tempQueue.enqueue(i + 10); 106 System.out.println("Enqueue, the queue is: " + tempQueue.toString()); 107 } // Of for i 108 109 for (int i = 0; i < 3; i++) { 110 tempValue = tempQueue.dequeue(); 111 System.out.println("Dequeue " + tempValue + ", the queue is: " + tempQueue.toString()); 112 } // Of for i 113 114 for (int i = 0; i < 6; i++) { 115 tempQueue.enqueue(i + 100); 116 System.out.println("Enqueue, the queue is: " + tempQueue.toString()); 117 } // Of for i 118 119 }// Of main 120 121 }// Of CircleIntQueue

浙公网安备 33010602011771号