Leetcode 147. Insertion Sort List (python version)

Source: Internet
Author: User

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)

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.