本文参考代码随想录

思路
方法一
把链表放进双向队列,然后通过双向队列一前一后弹出数据,来构造新的链表。
python
# 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.
"""
d = collections.deque()
tmp = head
while tmp.next:
d.append(tmp.next)
tmp = tmp.next
tmp = head
while len(d):
tmp.next = d.pop()
tmp = tmp.next
if len(d):
tmp.next = d.popleft()
tmp = tmp.next
tmp.next = None
方法二
将链表分割成两个链表,然后把第二个链表反转,之后在通过两个链表拼接成新的链表。

python
# 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.
"""
fast, slow = head, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
right = slow.next
slow.next = None
right = self.reverseList(right)
left = head
while right:
curLeft = left.next
left.next = right
left = curLeft
curRight = right.next
right.next = left
right = curRight
def reverseList(self, head):
cur = head
pre = None
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
```