快慢指针找中点
反转后半段 注意将原后半段的头结点的next清空
将反转后的后半段的节点 插入到前半段的两两节点间
# 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 head == None or head.next == None or head.next.next == None:
return head
slow = head
fast = head
while fast.next != None and fast.next.next != None:
fast = fast.next.next
slow = slow.next
back_head = slow.next
##print(back_head)
xx,reverse_head = self.reverse(back_head)
xx.next = None
slow.next = None
cur1 = head
last_next = reverse_head
#print(reverse_head)
while last_next != None:
nextnext = cur1.next
cur1.next = last_next
last_next = last_next.next
cur1.next.next = nextnext
cur1 = cur1.next.next
return head
def reverse(self,root):
if root == None:
return None,None
if root.next == None:
return root,root
elif root.next != None:
new_head,reverse_head = self.reverse(root.next)
new_head.next = root
return root,reverse_head