队列
简介:
1)队列是一个有序列表,可以用数组或链表实现。
2)先入先出。
使用场景:排队。
数组实现列表:
1)自定义一个实体类:front(头指针,默认-1),rear(尾指针,默认-1),arr(存放数组),maxSize(数组最大值)
2)当 front == rear 时,数组为空
3)当 rear < maxSize - 1 时,数组没满
4)当数组没满时,可继续加数据, arr[rear + 1]
4)当数组不为空时,可取数据,arr[front + 1]
代码如下:
public class ArrayQueue { private int maxSize; private int front; private int rear; private int[] arr; public ArrayQueue(int maxSize) { this.maxSize = maxSize; this.arr = new int[maxSize]; this.front = -1; this.rear = -1; } public boolean isFull() { return rear == maxSize - 1; } public boolean isEmpty() { return front == rear; } public void addQueue(int data) { if (isFull()) { System.out.println("队列满,不能加入~~"); return; } rear ++; arr[rear] = data; } public int getQueue() { if (isEmpty()) { throw new RuntimeException("队列为空,没有数据~~~"); } front ++; return arr[front]; } public void showQueue() { if (isEmpty()) { System.out.println("队列为空,没有数据~~~"); return; } for (int i = 0; i < arr.length; i ++) { System.out.printf("arr[%d]=%d\n", i, arr[i]); } } public int headQueue() { if (isEmpty()) { throw new RuntimeException("队列为空,没有数据~~~"); } return arr[front + 1]; } }
数组优化实现环形队列:
1)自定义一个类:front(头指针,默认0),rear(尾指针,默认0),maxSize(数组容量),arr(存放数组)
2)当 front == rear 时,数组为空
3)当 (rear + 1) % maxSize ! = front 时,数组没满
4)当数组没满时,可继续加数据, arr[rear],rear = (rear + 1) % maxSize
4)当数组不为空时,可取数据,arr[front],front = (front + 1) % maxSize
代码如下:
public class CircleArrayQueueD { private int maxSize; private int front; private int rear; private int[] arr; public CircleArrayQueueD(int maxSize) { this.maxSize = maxSize; arr = new int[maxSize]; this.front = 0; this.rear = 0; } public boolean isFull() { return (rear + 1) % maxSize == front; } public boolean isEmpty() { return rear == front; } public void addQueue(int data) { if (isFull()) { System.out.println("队列满,不能加入~~"); return; } arr[rear] = data; rear = (rear + 1) % maxSize; } public int getQueue() { if (isEmpty()) { throw new RuntimeException("队列为空,没有数据~~~"); } int value = arr[front]; front = (front + 1) % maxSize; return value; } public void showQueue() { if (isEmpty()) { System.out.println("队列为空,没有数据~~~"); return; } for (int i = front; i < front + size(); i ++) { System.out.printf("arr[%d]=%d\n", i % maxSize, arr[ i% maxSize]); } } public int size() { return (rear + maxSize - front) % maxSize; } public int headQueue() { if (isEmpty()) { throw new RuntimeException("队列为空,没有数据~~~"); } return arr[front]; } }

浙公网安备 33010602011771号