导语
队列是一种受限的线性表数据结构,它只允许前端进行删除操作,后端进行插入操作。队列中特殊的有循环队列、阻塞队列、并发队列。
队列分类
由数组组成的成为顺序队列,由链表实现的是链式队列。
顺序队列
public class ArrayQueue {
//定义一个数组items,大小n
private String[] items;
private int n = 0;
public ArrayQueue(int capacity) {
items = new String[capacity];
n = capacity;
}
//定义队头下标和队尾下标
private int head = 0;
private int tail = 0;
//入队
public boolean enqueue(String item) {
if (tail != n) {
items[tail] = item;
tail++;
return true;
} else {
if (head == 0) return false;
for (int i = head; i < n; i++) {
items[i - head] = items[i];
}
tail -= head;
head = 0;
items[tail] = item;
tail++;
return true;
}
}
//出队
public String dequeue() {
if (tail == head) return null;
String item = items[head];
head++;
return item;
}
}
如果头标记和尾标都在右移,可能出现tail==n,head == tail-1 ,head 前边的数据空间都不能被利用的情况,这里入列时要考虑数据搬移。
链式队列
public class LinkQueue {
private LinkNode head;
public LinkQueue() {
}
//入列
public void enqueue(int data) {
LinkNode newHead = new LinkNode(data);
if (head == null) {
head = newHead;
}
head.next = newHead;
}
//出列
public int dequeue() {
if (head == null) return 0;
int data = head.data;
head = head.next;
return data;
}
}
循环队列
循环队列可以有效解决数据搬移问题
public class CircularQueue {
private String[] items;
private int head;
private int tail;
private int n;
public CircularQueue(int capacity) {
items = new String[capacity];
n = capacity;
}
public String dequeue() {
if (head == tail) return null;
String item = items[head];
head++;
return item;
}
//队满时的规律是 (tail + 1) % n == head
public boolean enqueue(String item) {
if ((tail + 1) % n == head) return false;
items[tail] = item;
tail = (tail + 1) % n;
return true;
}
}
阻塞队列&并发队列
类似于生产者和消费者模式,我们可以使用阻塞队列来实现。比如BlockingQueue