Insert sort of linked list
Insertion Sort List
1) Basic ideas:In the set of numbers to be sorted, assuming that the number of front (n-1) [n>=2] is already in the order, now the nth number is inserted into the ordinal number in front, so that the n number is also in order. There is no way to randomly read a linked list. So insert sort, for each node, can only start from the head node, slowly backward to start the comparison, if the location is found to insert the node in the sequence. The code is as follows, Leetcode accept.
/** 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| | head->next = =NULL)returnHead; ListNode* Dummy =NewListNode (-1); Dummy->next =Head; ListNode* Pre =Head; ListNode* cur = head->next;//start with a second node while(cur) {if(Pre->val > Cur->val)//This assumes that there is a good order between the head node and the pre node.{ListNode*tmp =dummy; while(tmp->next->val<cur->val) tmp= tmp->Next; Pre->next = cur->next;//connect the pre to the node behind the curCur->next = tmp->next;//cur Insert the appropriate positionTmp->next =cur; } ElsePre= pre->Next; Cur= pre->Next; } returnDummy->Next; }};
List Sort---list insert sort