educative.io

Question on Linked List 'Insertion in a Singly Linked List' program

For the linked list insertion program, i got a question.
public void printList() {
if (isEmpty()) {
System.out.println(“List is Empty!”);
return;
}

    Node temp = headNode;
    System.out.print("List : ");
    while (temp.nextNode != null) {
        System.out.print(temp.data.toString() + " -> ");
        temp = temp.nextNode;
    }
    System.out.println(temp.data.toString() + " -> null");
}

for the above piece of code, when the linked list have only element, so the nextNode will be null.
So, the printList() method will not print any elements even though linked list is not empty.

can anyone confirm.??

1 Like

Yes Bro, I also come across this line. Later I found that It should be like this:
while (temp != null)