Topic:
sort a linked list using insertion sort.
The main idea is to implement a list of insert sort
algorithm idea:
one node
For each node with the idea of inserting a sort into the new ascending list of lists
Here's a small trick,leetcode that has a set of data that is 1~4999 ascending sequence if we use the above method will time out
So we set a last bit when we insert the sort, and we record where we are currently inserted.
At the next insertion time compared to the last insertion position, if the current Node.val > Last.val, then we can only start from the previous lookup, because the preceding node Val is smaller than the nodes Val, there is no need to find.
Code:
Class solution (object): def addinlist (Self, head, last, node): iterator = head if last.val <= node.val: iterator = last while iterator.next: if iterator.next.val > node.val: node.next = iterator.next iterator.next = node return iterator &nBsp; iterator = iterator.next iterator.next = node return iterator Def insertionsortlist (Self, head): "" " :type head: ListNode :rtype: ListNode "" " if head == None or head.next == None: return head start = listnode ( -2147483648) last = start while head: next = head.next head.next = none last = self.addinlist (Start, last, head) head = next return start.next
This article is from the "11139828" blog, please be sure to keep this source http://11149828.blog.51cto.com/11139828/1737499
Leetcode 147. Insertion Sort List (python version)