List Sort---list insert sort

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.