码迷,mamicode.com
首页 > 编程语言 > 详细

【leetcode】Reorder List (python)

时间:2017-05-02 14:03:16      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:fast   list   node   ast   out   技术   部分   .net   alt   

问题的思路是这样:

技术分享

循环取头部合并,事实上也能够换个角度来看,就是将后面的链表结点,一次隔空插入到第一部分的链表中。

class Solution:
    # @param head, a ListNode
    # @return nothing
    def reorderList(self, head):
        if None == head or None == head.next:
            return head
        #找到中间点,截断
        pfast = head
        pslow = head
        
        while pfast.next and pfast.next.next:
            pfast = pfast.next.next
            pslow = pslow.next
        pfast = pslow.next
        pslow.next = None
        
        #将第二部分的结点逆置
        pnext = pfast.next
        pfast.next = None
        while pnext:
            q = pnext.next
            pnext.next = pfast
            pfast = pnext
            pnext = q
        #将逆置后的链表隔空插入到第一部分
        tail = head
        while pfast:
            pnext = pfast.next
            pfast.next = tail.next
            tail.next = pfast
            tail = tail.next.next
            pfast = pnext
        return head


【leetcode】Reorder List (python)

标签:fast   list   node   ast   out   技术   部分   .net   alt   

原文地址:http://www.cnblogs.com/yxysuanfa/p/6795447.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!