Reorder List

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

这是一道比较综合的链表题目。一开始拿到手足无措。慢慢分析了一下,其实做法无非分三步:

1.将链表分为前后两端。

2.将后一段链表前后反转。

3.合并两段链表。

思路简单,由于合并了好几段代码,需要注意坑。代码如下:

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: void Do not return anything, modify head in-place instead.
        """
        if not head or not head.next or not head.next.next:
            return 
            
        slow = fast = head
        #找中点,slow为前一段的最后一个结点
        while fast.next and fast.next.next:
              fast = fast.next.next
              slow = slow.next
         
        cur = slow.next    #下一段的头结点
        slow.next = None   #彻底割断前一段

#反转后一段 pre
= None 注意<pre,cur>的结点对一定要以None开头,使原来的头结点next为None,彻底割裂联系 while cur: tmp = cur.next cur.next = pre pre = cur cur = tmp cur = head #pre is the start of second part while pre and cur: tmp1 = cur.next cur.next = pre tmp2 = pre.next pre.next = tmp1 cur = tmp1 pre = tmp2 return

可以看到时间复杂度为O(n),空间复杂度为O(1)

转载于:https://www.cnblogs.com/sherylwang/p/5551204.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值