前面写了用动态数组实现队列,现在我将用带有尾指针的链表实现队列。
我们知道队列需要在两端进行操作,如果是以普通链表进行底层实现的队列,在入队时需要找到最后一个节点才能进行添加元素,这样相当于遍历一遍链表,从而造成巨大的时间浪费。
为了解决这个问题,我们引入了尾指针的概念,即始终使用tail作为最后一个节点,这样我们在入队时就能直接操作,无需在链表中遍历寻找最后一个节点的位置。
-------------------------------------------------------------------------------------------------------------------------------------------------
实现接口:Queue<E>
实现类:LinkedListQueue<E>
因为带有尾指针,故不再复用前面写的不带有尾指针的LinkedList链表类。
-------------------------------------------------------------------------------------------------------------------------------------------------
public class LinkedListQueue<E> implements Queue<E> {
/*
* 创建只允许本类调用的内部类(节点类)
*/
private class Node {
public E e;
public Node next;
// 内部类构造方法
public Node(E e, Node next) {
this.e = e;
this.next = next;
}
public Node(E e) {
this.e = e;
this.next = null;
}
public Node() {
this(null, null);
}
@Override
public String toString() {
return e.toString();
}
}
private Node dummyHead, tail;// 虚拟头结点和尾节点
private int size;
// 带有尾指针的链表构造方法
public LinkedListQueue() {
dummyHead = new Node();
tail = new Node();
size = 0;
}
@Override
public void enqueue(E e) {
if (tail.e== null) {// 尾节点为空,也意味着头节点为空
tail = new Node(e);
dummyHead.next = tail;// 只含一个元素,此时头结点等于尾节点
} else {
tail.next = new Node(e);
tail = tail.next;
}
size++;
}
@Override
public E dequeue() {
if (isEmpty())
throw new IllegalArgumentException("操作失败!链表为空!");
Node head = dummyHead.next;
dummyHead.next = head.next;
head.next = null;
size--;
return head.e;
}
@Override
public E getFront() {
return dummyHead.next.e;
}
@Override
public int getSize() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("Queeu: top ");
for (Node cur = dummyHead.next; cur != null; cur = cur.next)
res.append(cur + "->");
res.append("NULL tail");
return res.toString();
}
}