public class SqQueue { int[] data; int front, rear; SqQueue() { data = new int[30]; front = rear = -1; } boolean empty() { return front == rear; } boolean enQueue(int e) { if(rear == 29) return false; rear++; data[rear] = e; return true; } int[] deQueue() { int[] arr = new int[2]; if(front == rear) { arr[0] = 0; return arr; } arr[0] = 1; front++; arr[1] = data[front]; return arr; } void display() { for(int i=front+1; i<=rear; i++) { if(i != rear) { System.out.print(data[i] + "->"); } else { System.out.println(data[i]); } } } public static void main(String[] args) { SqQueue sq = new SqQueue(); System.out.println(sq.empty()); sq.enQueue(4); sq.enQueue(5); sq.display(); sq.deQueue(); sq.deQueue(); System.out.println(sq.empty()); sq.display(); sq.enQueue(1); sq.enQueue(3); sq.display(); sq.deQueue(); sq.display(); sq.enQueue(2); sq.deQueue(); sq.display(); System.out.println(sq.empty()); } }
结果:
true 4->5 true 1->3 3 2 false
ps:1、队空条件为 front==rear
2、队满条件为rear==maxSize-1
3、队尾指针总是指向队列中队尾的元素,而队头指针总是指向队列中队头元素的前一个元素。