Leetcode "insertion Sort List" Python implementation

Source: Internet
Author: User

title :

Sort a linked list using insertion sort.

code : OJ Test via runtime:860 ms

1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8     #@param head, a listnode9     #@return a ListNodeTen     definsertionsortlist (Self, head): One          A          -         ifHead isNoneorHead.next isNone: -             returnHead the          -Dummyhead =listnode (0) -Dummyhead.next =Head -          +Curr =Dummyhead.next -          whileCurr.next is  notNone: +             ifCurr.next.val <Curr.val: APre =Dummyhead at                  whilePre.next.val <Curr.next.val: -Pre =Pre.next -TMP =Curr.next -Curr.next =Tmp.next -Tmp.next =Pre.next -Pre.next =tmp in             Else: -Curr =Curr.next to          +         returnDummyhead.next

Ideas :

The first thing to know is the principle of insertion sorting.

For a single-linked list, pointers need to be exchanged.

Small white memory insertion sorting principle only one sentence: analogy poker cards, the cards by size inserted.

The place to be aware of IS

Do not add extra judgment, otherwise it will time out; the first time I run, I add a pre! = Curr to the inside of the while loop condition, and the result is timed out.

Check the logic and find that it is useless to judge a waste of time, removed and passed.

Leetcode "insertion Sort List" Python implementation

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.