// dummy 3 4 1 5 // t t.n p p.n // prev public ListNode insertionSortList(ListNode head) { if (head == null || head.next == null) { // size == 0 OR 1 return head; } ListNodedummy=newListNode(-1); dummy.next = head; ListNodep= head.next; // start from the second node ListNodeprev= head; // otherwise it would compare with dummy
while (p != null) { ListNodet= dummy;
if (prev.val > p.val) { // p needs swapping (better performance) while (t.next != p && p.val > t.next.val) { t = t.next; } // stops at the right position prev.next = p.next; p.next = t.next; t.next = p; p = prev.next; // set next (prev not changing) } else { // p needs not swapping prev = p; p = p.next; } } return dummy.next; }