LeetCode 143. 重排链表
143. 重排链表
Difficulty: 中等
给定一个单链表 L:L0→_L_1→…→_L_n-1→_L_n ,
将其重新排列后变为: L0→_L_n→_L_1→_L_n-1→_L_2→_L_n-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
Solution
这题的难度应该不止中等,挺难的,操作有点复杂。参考题解:Java solution with 3 steps - LeetCode Discuss
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head or not head.next: return
p1 = p2 = head
# find the middle
while p2.next and p2.next.next:
p1 = p1.next
p2 = p2.next.next
# reverse the half after middle
mid = p1
pCurrent = p1.next
while pCurrent.next:
current = pCurrent.next
pCurrent.next = current.next
current.next = mid.next
mid.next = current
p1 = head
p2 = mid.next
while p1 != mid:
mid.next = p2.next
p2.next = p1.next
p1.next = p2
p1 = p2.next
p2 = mid.next