标签:
方法一:
为了能够充分地使用数组中的存储空间,把数组的前端和后端连接起来,形成一个环形的顺序表,即把存储队列元素的表从逻辑上看成一个环,称为环形队列,也叫循环队列。
ps:1、队空条件:front==rear
2、队满条件:(rear+1)%maxSize == front //少用一个空间,即最多放maxSize-1个元素。
3、初始化时front=rear=0;且从data[1]开始放元素。
4、队中元素个数为(rear-front+maxSize)%maxSize
5、队首指针进1:front=(front+1)%maxSize
队尾指针进1:rear=(rear+1)%maxSize
public class SqQueue { int[] data; int front, rear; SqQueue() { data = new int[30]; front = rear = 0; } boolean empty() { return front == rear; } boolean enQueue(int e) { if((rear+1)%30 == front) return false; rear=(rear+1)%30; data[rear] = e; return true; } int[] deQueue() { int[] arr = new int[2]; if(front == rear) { arr[0] = 0; return arr; } arr[0] = 1; front=(front+1)%30; arr[1] = data[front]; return arr; } void display() { int count = (rear-front+30)%30; for(int i=0; i<=count-1; i++) { if(i != count-1) { System.out.print(data[(i+front+1)%30] + "->"); } else { System.out.println(data[(i+front+1)%30]); } } } 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()); } }
方法二:
如果知道了队头指针和队列中的元素个数,就可以计算出队尾指针。
ps: 1、rear = (front+count)%maxSize
2、队空条件 count==0,队满条件 count == maxSize
3、与方法一的区别是该队列最多可以放置maxSize个元素。
4、初始化时front=0,count=0
public class SqQueue { int[] data; int front, count; SqQueue() { data = new int[30]; front = count = 0; } boolean empty() { return count==0; } boolean enQueue(int e) { if(count==30) return false; int rear = (front+count)%30; rear=(rear+1)%30; data[rear] = e; count++; return true; } int[] deQueue() { int[] arr = new int[2]; if(count == 0) { arr[0] = 0; return arr; } arr[0] = 1; front=(front+1)%30; arr[1] = data[front]; count--; return arr; } void display() { for(int i=0; i<=count-1; i++) { if(i != count-1) { System.out.print(data[(i+front+1)%30] + "->"); } else { System.out.println(data[(i+front+1)%30]); } } } 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
标签:
原文地址:http://blog.csdn.net/qhairen/article/details/46457327