队列是一种只允许在一端插入数据(队尾),在另一端删除数据(队头)的操作的特殊线性表。
队列的特点:先进先出
队列可以用数组实现,称为顺序队列,又叫循环队列。也可以用链表实现,称为链式队列。
链式队列:
package queue.com;
public class MyListQueue {
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
Node front;
Node rear;
int usedSize;
//判断是否为空
public boolean isEmpty() {
return usedSize == 0;
}
// 入队(尾插)
public void offer(int data) {
Node node = new Node(data);
if (isEmpty()) {
this.front = node;
this.rear = node;
} else {
this.rear.next = node;
this.rear = node;
}
this.usedSize++;
}
//出队(从头出)
public int poll() {
int tmp = this.front.data;
this.front = this.front.next;
this.usedSize--;
return tmp;
}
//弹出队头元素
public int peek() {
return this.front.data;
}
}
顺序队列(循环队列):
package queue.com;
public class MyCircularQueue {
public int[] elem;
public int front;
public int rear;
public int usedSize;
public MyCircularQueue(int k) {
this.elem = new int[k];
this.front = 0;
this.rear = 0;
this.usedSize = 0;
}
//进队列
public boolean enQueue(int value) {
if (isFull()) {
return false;
}
this.elem[rear] = value;
this.rear = (this.rear + 1) % this.elem.length;
this.usedSize++;
return true;
}
//出队列
public boolean deQueue() {
if (isEmpty()) {
return false;
}
this.front = (this.front+1) % this.elem.length;
this.usedSize--;
return true;
}
//弹出队头元素
public int Front() {
if(isEmpty()) {
return -1;
}
return this.elem[this.front];
}
//弹出队尾元素
public int Rear() {
if(isEmpty()) {
return -1;
}
int index = this.rear == 0 ? index = this.elem.length-1 : this.rear-1;
return elem[index];
}
public boolean isEmpty() {
return this.front == this.rear;
}
public boolean isFull() {
return this.front == (this.rear+1)%this.elem.length;
}
}
来源:CSDN
作者:嘿heh
链接:https://blog.csdn.net/qq_41185460/article/details/103493425