* dayFour(二) * 和线性表类似,队列也可以有两种存储表示。 * 用链表表示的队列简称为链队列。 * 链队列的操作即为单链表的插入和删除操作的特殊情况,只是尚需修改尾指针或头指针。 * 以下为链队列的实现。
public class LinkQueue<T> { private class QNode<T>{ private T data; private QNode<T> next; /** * 默认无参初始化 */ private QNode(){ this.data = null; this.next = null; } /** * 有参构造 * @param data 要存入的数据 */ private QNode(T data){ this.data = data; this.next = null; } } //头指针 private QNode<T> front; //尾指针 private QNode<T> rear; //队列数据容量 private int length; /** * 无参构造,创建一条无数据的队列 */ public LinkQueue(){ this.front = new QNode<>(); this.rear = new QNode<>(); this.length = 0; } /** * 初始化队列 */ public void initQueue(){ this.front = null; this.rear = null; this.length = 0; } /** * 队列判空 * @return true为空,false为满 */ public boolean isNull(){ return (front.next == null || rear.next == null); } /** * 元素入队 * @param data 要传入的元素数据 */ public void enQueue(T data){ if (isNull()){ front.next = new QNode<>(data); rear.next = new QNode<>(data); } else { QNode<T> tqNode = new QNode<>(data); tqNode.next = front.next; front.next = tqNode; length++; } } /** * 元素出队 * @return 出队元素 */ public T deQueue(){ if (isNull()){ throw new RuntimeException("队列空,无法移除"); } else if (length == 1){ T qNode = front.next.data; initQueue(); return qNode; } else { QNode<T> qNode = front; for (int i = 1; i < length - 1; i++) { qNode = qNode.next; } QNode<T> node = rear.next; rear.next = qNode.next; length--; return node.data; } } }