队列的实现有两种:顺序映像、非顺序映像,顺序映像的底层是
循环数组,非顺序映像的底层是
单向链表。
1 队列的顺序映像
import com.cskaoyan.exception.EmptyQueueException;
public class MyQueue {
private static final int MAX_CAPACITY = Integer.MAX_VALUE - 8;
private static final int DEFAULT_CAPACITY = 10;
private int front;
private int rear;
private int size;
private String[] elements;
public MyQueue() {
elements = new String[DEFAULT_CAPACITY];
front = 0;
rear = elements.length - 1;
}
public MyQueue(int capacity) {
if (capacity > MAX_CAPACITY || capacity < 0) {
throw new IllegalArgumentException("capacity = " + capacity);
}
elements = new String[capacity];
front = 0;
rear = elements.length - 1;
}
public void enque(String s) {
if (size + 1 > elements.length) {
if (size + 1 > MAX_CAPACITY) {
throw new ArrayStoreException();
}
int len = elements.length + (elements.length >> 1);
if (len > MAX_CAPACITY || len < 0) {
len = MAX_CAPACITY;
}
int newLength = len > (size + 1) ? len : size + 1;
grow(newLength);
}
rear = (rear + 1) % elements.length;
elements[rear] = s;
size++;
}
private void grow(int newLength) {
String[] arr = new String[newLength];
for (int i = 0; i < size; i++) {
arr[i] = elements[(front + i) % elements.length];
}
elements = arr;
front = 0;
rear = size - 1;
}
public String deque() {
if (isEmpty()) {
throw new EmptyQueueException();
}
String retVal = elements[front];
front = (front + 1) % elements.length;
size--;
return retVal;
}
public String peek() {
if (isEmpty()) {
throw new EmptyQueueException();
}
return elements[front];
}
public boolean isEmpty() {
return size == 0;
}
}
自定义的EmptyQueueException:
public class EmptyQueueException extends RuntimeException {
public EmptyQueueException() {
super();
}
public EmptyQueueException(String message) {
super(message);
}
}
2 队列的应用场景
- 普通队列应用场景十分有限。
- 阻塞队列:
enque(): 当队列满时,阻塞,等待队列不满时,再入队列,并返回。 deque(): 当队列空时,阻塞,等待队列不空时,再出队列,并返回。 - 并发队列
线程安全的队列 - 缓存
- 广度优先遍历
结束语:如果本篇博客对您有帮助,请点赞、收藏或关注,您的鼓励是博主进步的动力,感谢支持,共同进步。
|