队列,又称为伫列(queue),是一种先进先出的线性表。在具体应用中通常用链表或者数组来实现。队列只允许在后端(称为rear)进行插入操作,在前端(称为front)进行删除操作。
队列的操作方式和堆栈类似,唯一的区别在于队列只允许新数据在后端进行添加。
本文来看看用数组实现的队列。
看一下队列的基本操作:
class QueueLink{
int[] arr;
int front;
int rear;
int usedSize = 0;
int maxSize = 10;
// 队列的大小初始化为10
public QueueLink() {
this(10);
}
public QueueLink(int size) {
arr = new int[size];
front = 0;
rear = 0;
}
/** 判断队列是否已满 */
public boolean isFull() {
// 可用语句return (rear + 1) % maxSize == front;实现该功能
if ((rear + 1) % maxSize == front) {
return true;
}
return false;
}
/** 元素入队列操作 */
public void push(int data) {
if(isFull()) {
return;
}
arr[rear] = data;
// 将rear移动到下一个数组单元
rear = (rear + 1) % maxSize;
// 已使用队列长度每次加1
usedSize++;
}
/** 判断队列是否为空操作 */
public boolean isEmpty() {
// 可以用语句 return front == rear;直接实现该功能
if(front == rear) {
return true;
}
return false;
}
/** 元素出队列操作 */
public void pop() {
if(isEmpty()) {
return;
}
// 将排除出去的元素置为-1,便于回收
arr[front] = -1;
// // 将front移动到下一个数组单元
front = (front + 1) % maxSize;
// 已使用队列长度每次减1
usedSize--;
}
/** 得到队列头元素操作 */
public int getTop() {
if(isEmpty()) {
return -1;
}
return arr[front];
}
/** 队列元素输出操作 */
public void print() {
// (x + 1) % maxSize语句可以将x移动到下一个数组单元,这是队列里的常用语句
for(int x = front; x < rear; x = (x + 1) % maxSize) {
System.out.print(arr[x] + " ");
}
System.out.println();
}
}
用一个例子来验证以上程序是否正确:
public class Test {
public static void main(String[] args) {
QueueLink queue = new QueueLink();
// 动态制作一个队列
for (int x = 0; x < 5; x++) {
queue.push(x);
}
System.out.print("队列内的元素是 :");
queue.print();
System.out.println("队列头元素是 :" + queue.getTop());
System.out.print("队列长度是 :" + queue.uesdSize());
System.out.println("=====================");
queue.pop();
System.out.print("执行一次出队列操作后的队列内元素是 :");
queue.print();
System.out.print("执行一次出队列操作后的队列头元素是 :" + queue.getTop());
System.out.print("执行一次出队列操作后的队列长度是 :" + queue.usedSize());
}
}
以上程序的输出结果是:
队列内的元素是 :0 1 2 3 4
队列头元素是 :0
队列长度是:5
=====================
执行一次出队列操作后的队列内元素是 :1 2 3 4
执行一次出队列操作后的队列头元素是 :1
执行一次出队列操作后的队列长度是:4