143.重排链表

143.重排链表
给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

实例1:
143.重排链表_第1张图片
输入:head = [1,2,3,4]
输出:[1,4,2,3]

实例2:
143.重排链表_第2张图片
输入:head = [1,2,3,4,5]
输出:[1,5,2,4,3]

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reorder-list

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: None Do not return anything, modify head in-place instead.
        """
        slow = head
        fast = slow.next
        while(fast and fast.next):
            slow = slow.next
            fast = fast.next.next
        l2 = slow.next
        slow.next = None
        cur = l2
        pre = None
        while cur:
            temp = cur.next
            cur.next = pre
            pre = cur
            cur = temp
        result = ListNode(0)
        re = result
        while pre and head:
            re.next = head
            re = re.next
            head = head.next
            re.next = pre
            re = re.next
            pre = pre.next
        if pre:
            re.next = pre
        if head:
            re.next = head
        return result.next

你可能感兴趣的:(leetcode刷题,链表,leetcode,python)