牛客NC2 重排链表,python3,自己的解法

思路是,先用快慢指针找到中点位置,把链表一分为二,把第二个链表反转,依次插入第一个链表中。

具体操作中有以下需要注意的地方:

1.如果是空,一个节点,两个节点的情况下,不用重排,直接返回;

2.反转链表这一步,注意判断条件

3.插入链表中这一步,注意停止条件。判断条件设置在第二个链表上,当一次插入结束后,如果第二个链表里已经没有元素了,即curNode == None,跳出循环

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reorderList(self , head ):
        # write code here
        if head is None:
            return 
        if head.next is None or head.next.next is None:
            return head
        fast = head
        slow = head

        while fast is not None:
            if fast.next is None:
                break
            elif fast.next.next is None:
                break
            fast = fast.next.next
            slow = slow.next

        l2 = slow.next
        slow.next = None
        l1 = head

        def researve(head):
            pre = None
            cur = head
            tmp = head.next
            while cur is not None:
                cur.next = pre
                pre = cur
                if tmp is None:
                    break
                cur = tmp
                # if tmp.next is None:
                #     break
                tmp = tmp.next
            
            return cur

        l1cur = l1
        l1then = l1.next
        l2cur = researve(l2)
        l2then = l2cur.next
        while 1:
            l1cur.next = l2cur
            l2cur.next = l1then
            l1cur = l1then
            l2cur = l2then
            if l2cur is None:
                break
            l1then = l1then.next      
            l2then = l2then.next
        
        return head

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值