思路:
1、使用双指针法找到链表中点,断开为2个链表
2、反转第2个链表
3、将第二个链表的元素间隔地插入第一个链表中
# 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: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
# 双指针寻找中点
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# slow为中点
l2 = slow.next
slow.next = None
l1 = head
# 反转p2
l2 = self.reverseList(l2)
#将p2依次插入到p1
self.insertList(l1, l2)
def reverseList(self, head):
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
def insertList(self, l1, l2):
while l1 and l2:
tmp1 = l1.next
tmp2 = l2.next
l1.next = l2
l1 = tmp1
l2.next = l1
l2 = tmp2