[Leetcode][python]Insertion Sort List

题目大意

通过插入排序的方法排序一个链表。

解题思路

参考:http://www.cnblogs.com/zuoyuan/p/3700105.html
这里写图片描述

代码

class Solution(object):
    def insertionSortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return head
        dummy = ListNode(0)
        dummy.next = head
        curr = head
        while curr.next:
            if curr.next.val < curr.val:  # 直到某数小于其前面的数,进入
                pre = dummy  # 回到头开始往后遍历                        
                while pre.next.val < curr.next.val:  # 用pre直到找到应该插入的位置
                    pre = pre.next
                # 如上图
                tmp = curr.next                     
                curr.next = tmp.next
                tmp.next = pre.next
                pre.next = tmp
            else:
                curr = curr.next
        return dummy.next

总结

猜你喜欢

转载自blog.csdn.net/qqxx6661/article/details/78818256