一、链式队列
队列的链式表示称为链式队列,其实也就是一个操作受限的单链表。
要一个单链表具有队列的性质,即先进先出,在编写代码之前,需要明确:
-
入队:链表添加元素也就是入队列需要采用的是尾插法,即在队尾添加元素;
-
出队:队列不为空时,出队列应该为删除头结点后的第一个结点;
如图:
二、实现一个链式队列
- 数据结构
class Queue<E> {
class Entry<E> {
E data;
Entry<E> next;
public Entry() {
this.data = null;
this.next = null;
}
public Entry(E val) {
this.data = val;
this.next = null;
}
}
private Entry<E> front; //头指针 也就是队首
private Entry<E> rear; //尾指针 即队尾
private int usedSize; //队列元素个数
public Queue() {
this.front = null;
this.rear = null;
this.usedSize = 0;
}
}
- 具体操作
- 判空
//判空
public boolean isEmpty() { //当usedSize等于时说明队列为空
return this.usedSize == 0;
}
}
- 获取队列长度
public int getUsedSize() {
return usedSize; //外部可以获取队列中元素的个数
}
- 入队列
//入队列
public void push(E val) {
Entry<E> entry = new Entry<>(val);
if (isEmpty()) { //在空队列第一个有元素入队时,需指定头指针与尾指针
this.front = entry; //此时头尾指针都是entry
this.rear = front;
} else { //队列不为空时,入队操作只需将新的元素结点放在rear的后面,然后rear指针后移
this.rear.next = entry;
this.rear = rear.next;
}
this.usedSize++;
}
- 出队列
//出队列
public void pop() {
if (isEmpty()) { //在出队操作时首先要判断队列是否为空
throw new UnsupportedOperationException("不支持的操作");
}
//当队列不为空时,删除front指针所指结点,只需将front指针后移即可
this.front = this.front.next;
this.usedSize--;
}
- 获取队首元素
//获取队首元素
public E peek() {
if (isEmpty()) { //在队列是否为空时队首元素不存在
throw new UnsupportedOperationException("不支持的操作");
}
//当队列不为空时,只需返回front指针所指结点元素值即可
return this.front.data;
}
- 打印队列元素
//打印
public void show() {
Entry cur = this.front;
while (cur != null) {
System.out.print(cur.data + " ");
cur = cur.next;
}
System.out.println();
}