目录
队列的使用
队列的模拟实现(链式结构)
public class MyQueue {
static class ListNode {
public int val;
public ListNode prev;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public ListNode head;
public ListNode last;
public void offer(int val) {
ListNode node = new ListNode(val);
if (head == null) {
head = last = node;
node.prev = last;
last = last.next;
}
}
public int poll() {
if (head == null) {
return -1;
}
int ret = head.val;
if (head.next == null) {
head = null;
last = null;
} else {
head = head.next;
head.prev = null;
}
return ret;
}
public int peek() {
if (head == null) {
return -1;
}
return head.val;
}
public boolean isEmpty() {
return head == null;
}
}
循环队列
class MyCircularQueue {
public int[] elem;
public int first;
public int last;
public MyCircularQueue(int k) {
elem = new int[k + 1];
}
public boolean enQueue(int value) {
if (isFull()) {
return false;
}
elem[last] = value;
last = (last + 1) % elem.length;
return true;
}
public boolean deQueue() {
if (isEmpty()) {
return false;
}
first = (first + 1) % elem.length;
return true;
}
// 得到对头元素
public int Front() {
if (isEmpty()) {
return -1;
}
return elem[first];
}
public int Rear() {
if (isEmpty()) {
return -1;
}
int index = (last == 0) ? elem.length - 1 : last - 1;
return elem[index];
}
public boolean isEmpty() {
return first == last;
}
public boolean isFull() {
return (last + 1) % elem.length == first;
}
}
双端队列(Deque)
双端队列(deque)是指允许两端都可以进行入队和出队操作的队列,deque 是 “double ended queue” 的简称。那就说明元素可以从队头出队和入队,也可以从队尾出队和入队。
Deque是一个接口,使用时必须创建LinkedList的对象。
在实际工程中,使用Deque接口是比较多的,栈和队列均可以使用该接口。
Deque<Integer> stack = new ArrayDeque<>();//双端队列的线性实现
Deque<Integer> queue = new LinkedList<>();//双端队列的链式实现