无法遍历java中链表中的所有元素



我在java中运行下面的简单链表程序,但缺少一个元素。我得到的输出
10
8
1

public class SinglyLinkedList {
ListNode head;
private static class ListNode {
int data;
ListNode next;

public ListNode(int data) {
this.data=data;
this.next = null;
}
}

public void display() {
ListNode curentNode = head;
while (curentNode.next != null) {
System.out.println(curentNode.data);
curentNode = curentNode.next;
}
}
public static void main(String[] args) {
SinglyLinkedList sll = new SinglyLinkedList();
sll.head =  new ListNode(10);
ListNode second = new ListNode(8);
ListNode third = new ListNode(1);
ListNode fourth = new ListNode(10);
sll.head.next = second;
second.next = third;
third.next = fourth;
sll.display();
}
}

您需要遍历LinkedList,直到节点不是null。如果当前节点不是null,则打印该节点的数据并继续前进。但如果您选中curentNode.next != null,则只能将数据打印到倒数第二个节点。

public class SinglyLinkedList
{
ListNode head;
private static class ListNode
{
int data;
ListNode next;
public ListNode(int data)
{
this.data=data;
this.next = null;
}
}
public void display()
{
ListNode curentNode = head;
while (curentNode != null) <------// Modified //
{
System.out.println(curentNode.data);
curentNode = curentNode.next;
}
}
public static void main(String[] args)
{
SinglyLinkedList sll = new SinglyLinkedList();
sll.head =  new ListNode(10);
ListNode second = new ListNode(8);
ListNode third = new ListNode(1);
ListNode fourth = new ListNode(10);
sll.head.next = second;
second.next = third;
third.next = fourth;
sll.display();
}
}

while条件检查列表中的下一项。你清单上的最后一项不符合你的条件。上一项的下一项始终为null。

更改条件

最新更新