Sort a linked list using insertion sort.
Hide TagsLinked List SortAnalysis: The chain list is divided into two parts: ordered and sorted, the order of the null end, cur inserted between preinsertion and insertion, next save Cur->next. Also, note that the use of dummy simplifies the insertion of head nodes.
Time complexity O (n^2), Space O (1)
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Insertionsortlist (listnode*head) { if(Head = =NULL)returnNULL; ListNode dummy (int_min); Dummy.next=Head; ListNode* Preinsertion =NULL; ListNode* Insertion =NULL; ListNode* cur = head->Next; Head->next = NULL;//Break the sorted and unsortedlistnode* next =NULL; while(cur) {preinsertion= &dummy; Insertion=Dummy.next; //find the right position while(Insertion! = NULL && cur->val >= insertion->val) {preinsertion= preinsertion->Next; Insertion= insertion->Next; }#if0if(insertion = = NULL)//cur is max, and don ' t need to move it{Next= cur->next;//just store cur first;Preinsertion->next =cur; Cur->next =NULL; Cur=Next; } Else{Next= cur->next;//just store cur first;Preinsertion->next =cur; Cur->next =insertion; Cur=Next; }#endifNext= cur->next;//just store cur first;Preinsertion->next =cur; Cur->next =insertion; Cur=Next; } returnDummy.next; }};
[Leetcode] Insertion Sort List