给定一个单链表 L 的头节点 head ,单链表 L 表示为:
L0 → L1 → … → Ln-1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入: head = [1,2,3,4]
输出: [1,4,2,3]
示例 2:
输入: head = [1,2,3,4,5]
输出: [1,5,2,4,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: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
def reserve(head):
pre, cur = None, head
while cur:
tmp = cur.next
cur.next = pre
pre, cur = cur, tmp
return pre
pre = ListNode()
pre.next = head
fast = slow = pre
while fast and fast.next:
fast = fast.next.next
slow = slow.next
half = slow.next
slow.next = None
rev_half = reserve(half)
cur = pre.next
while slow and rev_half:
tmp = cur.next
cur.next = rev_half
cur = cur.next
rev_half = rev_half.next
cur.next = tmp
cur = cur.next
09-14
1432
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-12
1873
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-16
228
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交