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)

posted on 2016-06-01 21:46  Sheryl Wang  阅读(138)  评论(0编辑  收藏  举报

导航