![](/img/trans.png)
[英]Java: What is the best way to traverse and insert element into a ranked linked list?
[英]Not able to traverse all the element in linked list in 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 条件检查列表中的下一项。 您在列表中的最后一项不满足您的条件。 最后一项的下一项始终为空。
改变条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.