[Leetcode] Insertion Sort List

Source: Internet
Author: User

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

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.