前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[Leetcode][python]Insertion Sort List/对链表进行插入排序

[Leetcode][python]Insertion Sort List/对链表进行插入排序

作者头像
蛮三刀酱
发布2019-03-26 15:45:13
7190
发布2019-03-26 15:45:13
举报

题目大意

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

解题思路

参考:http://www.cnblogs.com/zuoyuan/p/3700105.html

这里写图片描述
这里写图片描述
  1. 用current往后找,找到比之前小的数。
  2. 每次都用pre从dummy开始,找到该插入的位置,插入。

代码

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  # 把2保存到temo               
                curr.next = tmp.next # 把4指向2的后面一位
                tmp.next = pre.next  # 2指向3
                pre.next = tmp  # 1指向2
            else:
                curr = curr.next
        return dummy.next

总结

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年12月16日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目大意
  • 解题思路
  • 代码
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档