leetcode刷题6:对单链表重新排序--reorder list

给定一个单链表:L0->L1->L3...Ln-1->Ln

变为L0->Ln->L1...


分析:

实际上就是首先对链表进行对半分。把后面一半逆序排序,之后和前面一部分进行交叉排列。

这里面对链表进行对半分比较难解决,回顾前面几道题:快慢指针。

使用一个快指针,一次走两步,一个慢指针一次走一步。

他们同时出发,则在快指针到链表尾部的时候,慢指针会指向链表对半分之后的第二部分子链表的表头。


算法伪代码就不写了上面的分析已经比较明晰:

python实现如下:

class Solution:




    def reverse(self,head):
        if head == None or head.next == None:
            return head
        pre = head
        cur = head.next
        nex = head.next.next
        pre.next = None
        cur.next = pre


        while nex != None:
            pre = cur
            cur = nex
            nex= nex.next
            cur.next = pre
        return cur
    def merge(self,h1,h2):
        tmp1 = h1
        tmp2 = h2


        while tmp1 != None  and tmp2 != None:
            tmp = tmp1
            tmp1 = tmp1.next
            tmp.next = tmp2
            tmp = tmp2
            tmp2 =tmp2.next
            tmp.next = tmp1


        return h1


        


    def reorderList(self,head):
        if head == None or head.next == None:
            return head
        first = head.next
        second = head.next.next




        while second != None:
            
            if second.next == None:
                break
            first = first.next


            second = second.next.next
        
        second = first.next
        first.next = None
        second = self.reverse(second)


        head = self.merge(head,second)
        return head

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值