其他分享
首页 > 其他分享> > [Lintcode]99. Reorder List/[Leetcode]143. Reorder List

[Lintcode]99. Reorder List/[Leetcode]143. Reorder List

作者:互联网

99. Reorder List/143. Reorder List

Description

Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln

reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …

Example
Given 1->2->3->4->null, reorder it to 1->4->2->3->null.

Challenge
Can you do this in-place without altering the nodes' values?

我的代码

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: The head of linked list.
    @return: nothing
    """
    def reorderList(self, head):
        # write your code here
        def reverse(head):
            left = head
            right = None
            while(left):
                tmp = left.next
                left.next = right
                right = left
                left = tmp
            return right
        def merge(l1,l2):
            head1 = l1
            head2 = l2
            while(l1 and l2):
                tmp1 = l1.next
                tmp2  = l2.next
                l1.next = l2
                l2.next = tmp1
                l1 = tmp1
                l2 = tmp2
            return head1
        def getmid(head):
            slow = head
            fast = head.next
            while(fast and fast.next):
                slow = slow.next
                fast = fast.next.next
            head2 = slow.next
            slow.next = None
            return head, head2
            
        if head == None:
            return None
        l1 ,l2= getmid(head)
        l2 = reverse(l2)
        head =  merge(l1,l2)   

思路
分割成两段,后面的翻转,最后插空合并

标签:head,143,Ln,List,next,l2,l1,Reorder,left
来源: https://www.cnblogs.com/siriusli/p/10376340.html