首页 > 编程语言 > 详细

【leetcode】Reorder List (python)

时间:2014-07-16 17:23:07      阅读:310      评论:0      收藏:0      [点我收藏+]

问题的思路是这样:

bubuko.com,布布扣

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

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),布布扣,bubuko.com

【leetcode】Reorder List (python)

原文:http://blog.csdn.net/shiquxinkong/article/details/37813711

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!