Insert and sort the linked list.
An animated demonstration of insertion sort is shown above. Starting with the first element, the list can be considered partially sorted (in black).
Each iteration removes an element (represented in red) from the input data and inserts it in place into the ordered list.
Insertion sort algorithm:
- The insertion sort is iterative, moving only one element at a time until all elements can form an ordered output list.
- In each iteration, the insertion sort removes only one element to be sorted from the input data, finds its proper position in the sequence, and inserts it.
- Repeat until all input data is inserted.
Example 1:
Input: 4 - > 2 - > 1 - > 3 Output: 1 - > 2 - > 3 - > 4
Train of thought:
First disconnect the first element of the list, by default an element is sorted. After marking the remaining elements as an unsorted list, each element in the unsorted list is compared with the head of the sorted list each time. If the head is larger, it is inserted directly before the head, and if the head is larger, it traverses each element in the sorted array in turn. Know to find an element larger than the current element, and then insert it in front of the element, if it has been traversing until the end is no larger than him, then insert it directly into the end. The code is as follows:
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode InsertionSortList(ListNode head) { if(head == null || head.next == null) return head; //Unordered list, default first element is ordered ListNode noFinish = head.next; head.next = null; //An ordered list ListNode current,finish; //Currt is an unsorted list. Each value finish is an ordered list. while(noFinish != null){ current = noFinish; noFinish = noFinish.next; current.next = null; //Disconnect to remove currently unsorted nodes if(head.val > current.val){ //Comparing with the first element in the sorted list current.next = head; head = current; continue; } finish = head; while(finish.next != null){ //Compare with each element behind the sorted list if(finish.next.val > current.val){ current.next = finish.next; finish.next = current; break; } finish = finish.next; } if(finish.next == null){ //Add directly to the last element finish.next = current; } } return head; } }