99. Reorder List

题目

https://www.lintcode.com/problem/reorder-list/description?_from=ladder&&fromId=2

实现

  1. 找到中点
  2. 中点之后的都要变成反序
  3. 最后相互交替链接起来

代码

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):
        if head is None or head.next is None:
            return head

        # 找中点
        p_slow = head
        p_fast = head
        while p_fast.next is not None and p_fast.next.next is not None:
            p_slow = p_slow.next
            p_fast = p_fast.next.next

        # 初始
        p_fast = p_slow.next
        p_slow.next = None
        p_next = p_fast.next
        p_fast.next = None

        # 反序
        while p_next is not None:
            p_temp = p_next.next
            p_next.next = p_fast

            p_fast = p_next
            p_next = p_temp

        tail = head
        while p_fast is not None:
            p_temp = p_fast.next
            p_fast.next = tail.next
            tail.next = p_fast

            p_fast = p_temp
            tail = tail.next.next

        return head

你可能感兴趣的:(99. Reorder List)