Last updated 5 years ago
Sort a linked list using insertion sort.
3 -> 2 -> 5 -> null 2 -> 3 -> 5 -> null
Insertion Sort dummy node for each node in the linked list insert the node into the sorted position end for return dummy.next; Insert stop when the next node.value > newNode.value Node temp = travel.next; travel.next = newNode; newNode.next = temp;
public ListNode insertionSortList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode dummy = new ListNode(Integer.MIN_VALUE); ListNode travel = head; while (travel != null) { ListNode temp = travel.next; insert(dummy, travel); travel = temp; } return dummy.next; } // assume head is not null private void insert(ListNode head, ListNode newNode) { ListNode travel = head; while (travel.next != null && travel.next.val < newNode.val) { travel = travel.next; } ListNode temp = travel.next; travel.next = newNode; newNode.next = temp; }