Source: Https://leetcode.com/problems/insertion-sort-list
Sort a linked list using insertion sort.
Method:
1. Use a prehead to point to the head node so that no special processing is required when inserting a node in front of the head node (that is, a node value is smaller than the head node)
2. Start the traversal from the head node, if the value of the next node of the current node is larger than the value of the current node, walk from the beginning to find the first node that is larger than the value of the next node of the current node and insert it in front of it, noting that the insertion requires simultaneous handling of the node's position and insertion position.
Time complexity, average O (n^2), preferably O (1), at which point the node itself is ordered, the worst O (n^2)
Space complexity, required auxiliary storage for O (1)
Stability, stability, elements with the same value are kept in relative order after sorting
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7 * }8 */9 classSolution {Ten PublicListNode insertionsortlist (ListNode head) { OneListNode Prehead =NewListNode (0); AListNode next =NULL, node =NULL, Tmpnode =NULL; -Prehead.next =head; - while(Head! =NULL) { theNext =Head.next; - if(Next! =NULL&& Next.val <head.val) { -node =Prehead; - while(Node.next! =NULL&& Node.next.val <=next.val) { +node =Node.next; - } +Tmpnode =Node.next; ANode.next =Next; atHead.next =Next.next; -Next.next =Tmpnode; -}Else { -Head =Head.next; - } - } in returnPrehead.next; - } to}//8 Ms
Insertion sort list (single-linked list insertion sort)