在此链接列表中,循环仅显示前两个数字(67,175)。如何使用LinkedList的所有元素并全部打印出来?该代码在哪里出错?
public class LinkedList {
private Node head;
public void insert(int data) {
Node direction = new Node(data);
direction.next = null;
if (head == null) {
head = direction;
} else {
Node following = head;
while (following.next == null) {
following.next = direction;
}
}
}
public void print() {
Node direction = head;
while (direction != null) {
System.out.println(direction.data);
direction = direction.next;
}
}
}
答案 0 :(得分:3)
您的insert
方法不正确。这个
Node following = head;
while (following.next == null) {
following.next = direction;
}
应该类似于
Node following = head;
while (following.next != null) {
following = following.next;
}
following.next = direction;
您当前的方法仅支持两个节点。您需要先跟随列表的末尾,然后追加新的Node
。