视频详解:https://www.bilibili.com/video/BV1sd4y1x7KN/?spm_id_from=333.788&vd_source=11069f01f7471094186b646e3a184ca3
一、反转链表
LeetCode 206题:https://leetcode.cn/problems/reverse-linked-list/description/
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
解析:
class Solution:def reverseList(self, head: ListNode) -> ListNode:cur, pre = head, Nonewhile cur:tmp = cur.next # 暂存后继节点 cur.nextcur.next = pre # 修改 next 引用指向pre = cur # pre 暂存 curcur = tmp # cur 访问下一节点return pre
二、反转指定区间链表
LeetCode 92题:https://leetcode.cn/problems/reverse-linked-list-ii/description/?envType=study-plan-v2&envId=top-interview-150
给你单链表的头指针 head
和两个整数 left
和 right
,其中 left <= right
。请你反转从位置 left
到位置 right
的链表节点,返回 反转后的链表 。
解析:
class Solution:def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:dummy = ListNode(next = head)p0 = dummyfor _ in range(left - 1):p0 = p0.nextpre = Nonecur = p0.nextfor _ in range(right - left + 1):tmp = cur.nextcur.next = prepre = curcur = tmpp0.next.next = curp0.next = prereturn dummy.next
三、k个一组反转链表
LeetCode 第25题:https://leetcode.cn/problems/reverse-nodes-in-k-group/description/
给你链表的头节点 head
,每 k
个节点一组进行翻转,请你返回修改后的链表。
k
是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k
的整数倍,那么请将最后剩余的节点保持原有顺序。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
class Solution:def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:n = 0cur = headwhile cur:n += 1cur = cur.nextdummy = ListNode(next = head)p0 = dummypre = Nonecur = p0.nextwhile n >= k :n -= kfor _ in range(k):tmp = cur.nextcur.next = prepre = curcur = tmptmp = p0.nextp0.next.next = curp0.next = prep0 = tmpreturn dummy.next