[LeetCode]143. Reorder List

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

Solution: 

divide the whole process to three steps:

1. find the median node 首先找出中间的结点

2. reverse the second half of the singly-linked list. (don't forget split into two lists)反转单链表的后半部分,然后将链表分成前后两个链表

3. merge these two lists. 再将两个链表合并。


Time Complexity: O(n)


Note: OJ doesn't require any return value.(No need to return the Node "head", but we should keep it there.)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param {ListNode} head
    # @return {void} Do not return anything, modify head in-place instead.
    def reorderList(self, head):
        if not head or not head.next or not head.next.next:
            return
        # find the median node
        fast = head
        slow = head
        while True:
            if fast:
                fast = fast.next
            else:
                break
            if fast:
                fast = fast.next
            else:
                break
            slow = slow.next

        # reverse the second half of the singly-linked list
        before = None
        cur = slow.next
        while cur:
            after = cur.next
            cur.next = before
            before = cur
            cur = after
        # split to two singly-linked list
        slow.next = None

        # merge two lists
        head1 = head
        head2 = before
        while head2:
            after_1 = head1.next
            after_2 = head2.next
            head1.next = head2
            head2.next = after_1
            head1 = after_1
            head2 = after_2
        return


你可能感兴趣的:(LeetCode,python)