给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorder-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
# 利用双指针
if not head:
return None
#找到链表的中间节点
#快慢指针
slow,fast = head,head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# 完成循环后slow 指向中间结点,fast 指向最后一个结点或者倒数第二个结点(奇数指向最后一个,偶数指向倒数第二个)
# print(slow.val)
per,cur = None,slow.next
slow.next = None
# 后半部分进行翻转
while cur:
nxt = cur.next
cur.next = per
per,cur = cur,nxt
# 交替合并
p,q = head,per
while q:
nxt = p.next
p.next = q
p,q = q,nxt
return head
翻转函数解析:
https://www.bilibili.com/video/BV1f4411E7Tm?from=search&seid=17986368072566486892