curr
is null
when the first call to insert
is made. So while
gets ignored for this time.
But as prev == null
evaluates to true, if block gets executed, essentially executing this line:
head = new ListNode(x, curr);
With that, head
no more remains null
, and any further calls to insert
may result in while
loop getting executed. Whether the while
loop will be executed depends on this expression:
x.compareTo(curr.getData()) > 0
If true
, while
gets executed, else not.