队列(存储结构数组)--Java实现
1 /*队列:其实也是一种操作受限的线性表 2 *特点:先进先出 3 *队尾指针:负责元素的进队 4 *队头指针:负责元素的出队 5 *注意:普通队--容易浪费空间,一般队列使用最多的就是循环队列--指针环绕 6 *队列的实现方式:数组/链表 7 *队列判空判满: 8 *1.按照队列中元素的个数 9 *2.按照队头和队尾指针的关系 10 *存在双端队列:每端都可以插入和删除,其变形可以是操作受限的双端队列 11 *队列的应用:其实很多现实世界的规则都是按照排队这种思想 12 * */ 13 public class MyQueue { 14 private int items;//队列元素的个数 15 private long[] arr;//存储数组 16 private int front;//队头指针 17 private int rear;//队尾指针 18 private int maxSize;//数组的长度 19 20 public MyQueue(int s) { 21 maxSize = s; 22 arr = new long[maxSize]; 23 front = 0; 24 rear = -1; 25 items = 0; 26 } 27 28 //进队--先加在取 29 public void insert(long key){ 30 if(rear == maxSize - 1){ 31 rear = -1; 32 } 33 arr[++rear] = key; 34 items++; 35 } 36 37 //出队--先取在加1 38 public long remove(){ 39 long num = arr[front++]; 40 if(front == maxSize){ 41 front = 0; 42 } 43 items--; 44 return num; 45 } 46 47 //获取队头 48 public long getFront(){ 49 return arr[front]; 50 } 51 52 //判空 53 public boolean isEmpty(){ 54 return items == 0; 55 } 56 57 public boolean isEmpty1(){ 58 return (rear + 1 == front ||(front + maxSize - 1 == rear)); 59 } 60 61 62 63 //判满 64 public boolean isFull(){ 65 return rear == maxSize; 66 } 67 68 public boolean isFull1(){ 69 return (rear + 2 == front ||(front + maxSize - 2 == rear)); 70 } 71 72 //获取队列元素个数 73 public int size(){ 74 return items; 75 } 76 77 public int size1(){ 78 if(rear >= front){ 79 return rear - front + 1; 80 } 81 else{ 82 return (maxSize - front) + (rear + 1); 83 } 84 } 85 86 //显示队列 87 public void displayQueue(){ 88 for(int i = front;i < rear;i++){ 89 System.out.print(arr[i] + " "); 90 } 91 System.out.println(); 92 } 93 94 95 }