二、队列
1、介绍
队列是一种先进先出的线性表,它只允许在一端(队尾)进行插入操作,在另一端(队头)进行删除操作。可以用数组或链表来实现,一般用链表来实现,简称为链队列,建立在内存的动态区。
2、队列的顺序存储实现
顾名思义,用顺序表的方法实现,通常用数组。队列的顺序储存结构:
下面用数组实现队列:
思想:队列出队入队动态图:
队列的特性:队尾插入,队头删除。那么,一个元素入队列,rear++;一个元素出队列,front++。
结论:看图可知
判空:起始状态,front == rear == -1,则空队列判定,front == rear。
判满:一个元素入队列,rear++,则满队列判定,rear == length() - 1。
代码示例:数组实现队列
1 // 用数组模拟队列 2 public class MyQueue<T> { 3 private T[] elementData; 4 private int front; 5 private int rear; 6 7 public MyQueue(int initialCapacity) { 8 if (initialCapacity > 0) { 9 this.elementData = (T[]) new Object[initialCapacity]; 10 } else if (initialCapacity == 0) { 11 this.elementData = (T[]) new Object[]{}; 12 } else { 13 throw new IllegalArgumentException("Illegal Capacity: " + 14 initialCapacity); 15 } 16 17 front = -1; 18 rear = -1; 19 } 20 21 // 入队 22 public boolean offer(T e) { 23 if (isFull()) { 24 System.out.println("队列满,不能添加~"); 25 return false; 26 } 27 rear++; 28 elementData[rear] = e; 29 return true; 30 } 31 32 // 出队 33 public T poll() { 34 if (isEmpty()) { 35 throw new RuntimeException("队空,没有任何数据~"); 36 } 37 front++; 38 return elementData[front]; 39 } 40 41 // 读取队头 42 public T peek() { 43 if (isEmpty()) { 44 throw new RuntimeException("队空,没有任何数据~"); 45 } 46 return elementData[front + 1]; 47 } 48 49 // 判空 50 public boolean isEmpty() { 51 return front == rear; 52 } 53 54 // 判满 55 private boolean isFull() { 56 return rear == elementData.length - 1; 57 } 58 59 // 获取队列元素的个数 60 public int size() { 61 return rear - front; 62 } 63 64 @Override 65 public String toString() { 66 if (isEmpty()) { 67 return "[]"; 68 } 69 70 StringBuilder builder = new StringBuilder(); 71 builder.append("["); 72 for (int i = front + 1; i < rear + 1; i++) { 73 builder.append(elementData[i]) 74 .append(","); 75 } 76 // 去掉最后一个, 77 builder.deleteCharAt(builder.length() - 1); 78 builder.append("]"); 79 80 return builder.toString(); 81 } 82 }