【leetcode】Reorder List (python)

问题的思路是这样:

【leetcode】Reorder List (python)

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

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)

上一篇:2.1-Java语言基础(关键字)


下一篇:java学习篇(一)从网络下载图片