Leetcode 147 Insertion Sort List

Sort a linked list using insertion sort.

以第一个元素head后面接null为起始数组,然后后面每个node插入排序,然而超时。

评论区的优化:双指针在原链表上插入排序,且只有在该node需要被插入开始处重置开始指针。

class Solution(object):
    def insertionSortList(self, head):
        cur = dummy = ListNode(0)
        while head:
            if cur and cur.val > head.val:
                cur = dummy
            while cur.next and cur.next.val < head.val:
                cur = cur.next
            cur.next, cur.next.next, head = head, cur.next, head.next
        return dummy.next

 

posted @ 2016-04-07 18:00  lilixu  阅读(131)  评论(0编辑  收藏  举报