[Leetcode] 147 对链表进行插入排序

在这里插入图片描述
 
思路:
这也太想直接用列表排序了(面试官:回去等通知吧)
思路题目已经明确了
对未排序部分循环插入已排序部分
用vis和unvis来表示两部分
记得将vis和unvis之间的链接打断
速度很慢,应该可以在插入的时候加一个直接到末位的判断,可能会减少很多时间

 

class Solution:
    def insertionSortList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        vis=head
        unvis=head.next
        vis.next=None
        def plugin(node,head):
            head0=head
            while(head):
                if node.val<head.val:
                    node.next=head
                    head0=node
                    break
                if head.next:
                    if node.val>=head.val and node.val<=head.next.val:
                        node.next=head.next
                        head.next=node
                        break
                    else:
                        head=head.next
                else:
                    head.next=node
                    break
            return head0
        while(unvis):
            temp=unvis
            unvis=unvis.next
            temp.next=None
            vis=plugin(temp,vis)
        return vis
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值