通过链表构造队列是一个算法基本功。而很多基本功,不一定是算法的,还可能是java基础的。我们一起来看一下问题。之前我一段代码是这么写的:
public class linkQueue {
private Node front;
private Node rear;
private int size;
public linkQueue() {
this.front = new Node(0);
this.rear = new Node(0);
}
public void push(int value) {
Node newNode = new Node(value);
Node temp = front;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
size++;
}
public int pull() {
if (front.next == null) {
System.out.println("队列已空");
}
Node firstNode = front.next;
front.next = firstNode.next;
size--;
return firstNode.data;
}
public void traverse() {
Node temp = front.next;
while (temp != null) {
System.out.print(temp.data + "t");
temp = temp.next;
}
}
static class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
}
}
}
然后再写个测试类:
public static void main(String[] args) {
linkQueue topic12linkQueue = new linkQueue();
topic12linkQueue.push(1);
topic12linkQueue.push(2);
topic12linkQueue.push(3);
// System.out.println("第一个出队的元素为:" + topic12linkQueue.pull());
System.out.println("队列中的元素为:");
topic12linkQueue.traverse();
}
这时候执行并没有什么问题,但是有个同学对push有疑问:既然有rear和font了,那为什么不直接让rear指向新结点,而font还是要遍历一遍呢?也就是为什么不能这么写:
public void push(int value) {
Node newNode = new Node(value);
rear.next = newNode;
rear = newNode;
size++;
}
如果调试一下,你会发现链表的size是对的,但是rear和font不正常,为什么呢?因为这里的font和rear是没有关联的,是两个独立变化的链表,构造函数没有将其关联起来,后面push和pull的时候是只操作了rear和font,这就导致两个链表一直都没有关联到一起。
如果要解决,可以在构造方法里这么写:
this.rear = front;
然后push方法就可以这么写了。
构造方法和push的完整代码:
public linkQueue() {
this.front = new Node(0);
//一个很巧妙的设计
this.rear = front;
}
public void push(int value) {
Node newNode = new Node(value);
rear.next = newNode;
rear = newNode;
size++;
}



