25. Leetcode 143. 重排链表 (链表-基础操作类-重排链表)
生活随笔
收集整理的這篇文章主要介紹了
25. Leetcode 143. 重排链表 (链表-基础操作类-重排链表)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個單鏈表 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]思路:先將鏈表拆分成前后兩半 A 和 B。后一半 B 逆轉成 C。再將 A 和 C 交叉合并。
例如:1->2->3->4->5 拆分成:A=1->2->3,B=4->5。然后把 B 逆轉 成 C=5->4。最后 A 和 C 交叉合并成 D=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."""if head == None or head.next == None:return# 1. 找到鏈表的中點fast = headslow = headwhile fast.next and fast.next.next:fast = fast.next.nextslow = slow.nextmid = slow# 2. 后半段指針反轉r_head = mid.nextmid.next = Nonecur = r_headpre = Nonewhile cur:nxt = cur.nextcur.next = prepre = curcur = nxtreverse_r_head = pre# 3. 后半段插入到前半段l = headr = reverse_r_headwhile r:l_nxt = l.nextr_nxt = r.nextr.next = l.nextl.next = rl = l_nxtr = r_nxtreturn head
總結
以上是生活随笔為你收集整理的25. Leetcode 143. 重排链表 (链表-基础操作类-重排链表)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 24. Leetcode 61. 旋转链
- 下一篇: 26. Leetcode 206. 反转