[Solved] Linked List in Java: Displaying last node incorrectly [closed]


Note: the start node does not hold an item, it just points to the first item’s node.

The problem is in the display method:

Node n = start.link;
do {
    System.out.print(n.data+" -> ");
    n = n.link;
} while(n.link != null);

Imagine the point where n is the second to last node. We enter the loop, print the second to last item, and set n=n.link, that is, the last node. Next we check n.link!=null, which turns out to be false because we are in the last node, so we don’t enter the loop again and the last item is therefore not printed.

Note also that if you display an empty list you’ll have a NullPointerException: n=start.link will set n=null, because you don’t have any nodes. Then, you enter the loop and try to print, which will raise the exception.

It can be fixed in several ways. For instance, we can check the current node n before actually printing:

Node n = start.link;
while(n != null){
    System.out.print(n.data+" -> ");
    n = n.link;
}

1

solved Linked List in Java: Displaying last node incorrectly [closed]