Reputation: 23
I'm running below simple linked list program in java, but I'm getting one element short.
The output I'm getting
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();
}
}
Upvotes: 0
Views: 173
Reputation: 43
Your while condition checks for next item in the list. Your last item in the list does not satisifies your condition. Last item's next item is always null.
change the condition
Upvotes: 0
Reputation: 909
You need to traverse the LinkedList till the node is not null
. If current node is not null
, print the node's data and move ahead. But if you check curentNode.next != null
you can print the data till second last node only.
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();
}
}
Upvotes: 1