[Leetcode] [JAVA] Insertion Sort List

Source: Internet
Author: User

Sort a linked list using insertion sort.

Simply insert the sort, write a function that inserts a value into the list, and then traverse the entire list, one by one inserting the value into the new list:

1   PublicListNode insertionsortlist (ListNode head) {2         if(head==NULL)3             return NULL;4ListNode re =NewListNode (head.val);5ListNode cur =Head.next;6          while(cur!=NULL)7         {8Re =Insert (Re, cur.val);9Cur =Cur.next;Ten         } One         returnre; A     } -      -      PublicListNode Insert (ListNode Head,intv) the     { -ListNode LN =NewListNode (v); -ListNode cur =head; -ListNode helper =NewListNode (0); +Helper.next =head; -ListNode pre =Helper; +          A          while(cur!=NULL) at         { -             if(v<cur.val) -             { -Pre.next =Ln; -Ln.next =cur; -                 returnHelper.next; in             } -Pre =cur; toCur =Cur.next; +         } -Pre.next =Ln; theLn.next =NULL; *         returnHelper.next; $}

Recursive implementations:

1  PublicListNode insertionsortlist (ListNode head) {2         if(head==NULL|| head.next==NULL)3             returnhead;4         intValue =Head.val;5         returnInsert (Insertionsortlist (Head.next), value);6     }7     8      PublicListNode Insert (ListNode Head,intv)9     {TenListNode LN =NewListNode (v); OneListNode cur =head; AListNode helper =NewListNode (0); -Helper.next =head; -ListNode pre =Helper; the          -          while(cur!=NULL) -         { -             if(v<cur.val) +             { -Pre.next =Ln; +Ln.next =cur; A                 returnHelper.next; at             } -Pre =cur; -Cur =Cur.next; -         } -Pre.next =Ln; -Ln.next =NULL; in         returnHelper.next; -}

[Leetcode] [JAVA] 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.