/*队列的典型用例
* 1.淘宝订单,满足先进先出
* 2.各类待办事项,如餐厅出餐等
* */
1.队列的操作
public class QueueTest {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
//元素入队
queue.offer(1);//队首
queue.offer(2);
queue.offer(3);
queue.offer(4);
//访问队首元素
System.out.println(queue.peek());
//元素出队
int pop = queue.poll();
for (Integer i : queue) {
System.out.println(i);
}
//获取元素长度
int size = queue.size();
//判断队列是否为空
boolean empty = queue.isEmpty();
}
}
2.链表实现队列
public class LinkedListQueue {
private ListNode front, rear;
private int queueSize;
public LinkedListQueue() {
front = null;
rear = null;
}
public ListNode getFront() {
return front;
}
/*获取队列长度*/
public int getQueueSize() {
return queueSize;
}
/*判断队列是否为空*/
public boolean isEmpty() {
return queueSize == 0;
}
/*入队*/
public void push(int n) {
ListNode listNode = new ListNode(n);
if (front == null) {
front = listNode;
rear = listNode;
} else {
rear.next = listNode;
rear = listNode;
}
queueSize++;
}
/*出队*/
public int pop() {
int num = peek();
front = front.next;
queueSize--;
return num;
}
/*访问队首元素*/
public int peek() {
if (isEmpty()) {
throw new IndexOutOfBoundsException("Queue is empty");
}
return front.getVal();
}
/*将链表转化为Array并返回*/
public int[] toArray() {
ListNode listnode = front;
int[] arr = new int[getQueueSize()];
for (int i = 0; i < arr.length; i++) {
arr[i] = listnode.getVal();
listnode = listnode.next;
}
return arr;
}
3.基于环形数组实现队列
class ArrayQueue {
private int[] nums; // 用于存储队列元素的数组
private int front; // 队首指针,指向队首元素
private int queSize; // 队列长度
public ArrayQueue(int capacity) {
nums = new int[capacity];
front = queSize = 0;
}
/* 获取队列的容量 */
public int capacity() {
return nums.length;
}
/* 获取队列的长度 */
public int size() {
return queSize;
}
/* 判断队列是否为空 */
public boolean isEmpty() {
return queSize == 0;
}
/* 入队 */
public void push(int num) {
if (queSize == capacity()) {
System.out.println("队列已满");
return;
}
// 计算队尾指针,指向队尾索引 + 1
// 通过取余操作实现 rear 越过数组尾部后回到头部
//例如头指针是5,数组容量是5,里面一共3个数,
// (3+5)%5=3,这三个数分别占索引5,1,2故尾指针为3
int rear = (front + queSize) % capacity();
// 将 num 添加至队尾
nums[rear] = num;
queSize++;
}
/* 出队 */
public int pop() {
int num = peek();
// 队首指针向后移动一位,若越过尾部,则返回到数组头部
front = (front + 1) % capacity();
queSize--;
return num;
}
/* 访问队首元素 */
public int peek() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return nums[front];
}
/* 返回数组 */
public int[] toArray() {
// 仅转换有效长度范围内的列表元素
int[] res = new int[queSize];
for (int i = 0, j = front; i < queSize; i++, j++) {
res[i] = nums[j % capacity()];
}
return res;
}
}