leetcode 刷题:插入排序链表

很基础,我是用三种=实现都TLE了.还请大家指教。。。

第一种,递归的:

def insertionSortList1(self,head):

if head == None:
            return head
        left = head.next
        head.next = None


        left = self.insertionSortList(left)
       
        if left==None:
            return head
        if head.val <= left.val:
            head.next = left
            return head
        else:
            ret = left
            while left.next !=None:
                if head.val <= left.next.val:
                    head.next=left.next
                    left.next = head
                    return left
                left = left.next


            left.next = head
            return ret


第二种,维护一个已经排好序的列表,从未排序列表中取出一个找到对的位置,插入操作不涉及拆链和接链。而是置换节点的值。

def insertionSortList2(self,head):

if head == None or head.next == None:
            return head
        else:
            cur = head.next
            while cur != None:
                tmp_h = head
                while tmp_h.val < cur.val and tmp_h != cur:
                    tmp_h = tmp_h.next


                pre_val = cur.val
                #print '\nhaha',pre_val
                while tmp_h != cur:
                    tmp_val = tmp_h.val
                    tmp_h.val = pre_val
                    pre_val = tmp_val
                    tmp_h = tmp_h.next
                tmp_h.val=pre_val


                cur = cur.next
        return head

第三种:和第二种方法一样,不同的是找到要插入位置之后,使用链表插入的方式。

def insertionSortList3(self,head):

if head == None or head.next == None:
            return head
        next_ = head.next.next
        pivot = head.next
        head.next = None
        pivot.next = None


        while True:
            if pivot.val <=head.val:
                pivot.next = head
                head = pivot
            else:
                tmp_h = head
                while tmp_h.next != None:
                    if pivot.val <= tmp_h.next.val:
                        pivot.next = tmp_h.next
                        tmp_h.next = pivot
                        break
                    tmp_h= tmp_h.next
                if tmp_h.next == None:
                    tmp_h.next=pivot


            pivot = next_
            if next_ == None:
                break
            next_=next_.next
            pivot.next = None
        return head



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值