队列
2019-11-29 本文已影响0人
TomGui
如何理解“队列”?
特点
- 先进先出,后进后出
- “操作受限”的线性表,队列尾部插入,队列头部删除
顺序队列和链式队列
- 顺序队列:数组实现的队列
- 链式队列:链表实现的队列
顺序队列
// 用数组实现的队列
public class ArrayQueue {
// 数组:items,数组大小:n
private String[] items;
private int n = 0;
// head表示队头下标,tail表示队尾下标
private int head = 0;
private int tail = 0;
// 申请一个大小为capacity的数组
public ArrayQueue(int capacity) {
items = new String[capacity];
n = capacity;
}
// 入队
public boolean enqueue(String item) {
// 如果tail == n 表示队列已经满了
if (tail == n) return false;
items[tail] = item;
++tail;
return true;
}
// 出队
public String dequeue() {
// 如果head == tail 表示队列为空
if (head == tail) return null;
// 为了让其他语言的同学看的更加明确,把--操作放到单独一行来写了
String ret = items[head];
++head;
return ret;
}
}
循环队列
数组实现
原本数组是有头有尾的,是一条直线。把首尾相连,形成一个环。
public class CircularQueue {
// 数组:items,数组大小:n
private String[] items;
private int n = 0;
// head表示队头下标,tail表示队尾下标
private int head = 0;
private int tail = 0;
// 申请一个大小为capacity的数组
public CircularQueue(int capacity) {
items = new String[capacity];
n = capacity;
}
// 入队
public boolean enqueue(String item) {
// 队列满了
if ((tail + 1) % n == head) return false;
items[tail] = item;
tail = (tail + 1) % n;
return true;
}
// 出队
public String dequeue() {
// 如果head == tail 表示队列为空
if (head == tail) return null;
String ret = items[head];
head = (head + 1) % n;
return ret;
}
}
阻塞队列
阻塞队列其实就是在队列基础上增加了阻塞操作。当队列为空时,从队列头部取数据会被阻塞;当队列已满时,那么插入数据的操作就会被阻塞。
并发队列
并发队列就是队列的操作多线程安全。