[Leetcode] Insertion Sort List

Source: Internet
Author: User

Well, life gets difficult pretty soon whenever the same operation on array is transferred to linked list.

First, a quick recap of insertion sort:

Start from the second element (simply a[1] head -> next -> val in array and the annoying in linked list), each time when we see a node valwith smaller than it previous node, we scan from the and find the position, which the current head node should is in Serted. Since a node may is inserted before head , we create a that new_head points to head . The insertion operation, however, is a little easier for linked list.

Now comes the code:

1 classSolution {2  Public:3listnode* Insertionsortlist (listnode*head) {4listnode* New_head =NewListNode (0);5New_head-Next =head;6listnode* pre =New_head;7listnode* cur =head;8          while(cur) {9             if(cur, next && cur, Next, Val < curval) {Ten                  while(Pre, next && pre, Next, Val < cur, nextval) OnePre = PreNext; A                 /*Insert cur, next after pre.*/ -listnode* temp = PreNext; -Pre, next = curNext; theCur next = cur, nextNext; -Pre-Next Next =temp; -                 /*Move pre back to New_head.*/ -Pre =New_head; +             } -             Elsecur = curNext; +         } Alistnode* res = New_headNext; at         DeleteNew_head; -         returnRes; -     } -};

[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.