In this linked list, the loop only dispalys the first two numbers (67,175). How to use all elements of LinkedList and printout them all? Where's mistake in this code?
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;
}
}
}
Your insert
method is incorrect. This
Node following = head;
while (following.next == null) {
following.next = direction;
}
should be something like
Node following = head;
while (following.next != null) {
following = following.next;
}
following.next = direction;
your current method only supports two nodes. You need to first follow to the end of the list and then append the new Node
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.