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