Python基础算法——反转链表

视频详解: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 ,请你反转链表,并返回反转后的链表。

Python基础算法——反转链表_第1张图片

解析:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur, pre = head, None
        while cur:
            tmp = cur.next # 暂存后继节点 cur.next
            cur.next = pre # 修改 next 引用指向
            pre = cur      # pre 暂存 cur
            cur = 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 的链表节点,返回 反转后的链表 。

Python基础算法——反转链表_第2张图片

解析:

class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        dummy = ListNode(next = head)
        p0 = dummy
        for _ in range(left - 1):
            p0 = p0.next

        pre = None
        cur = p0.next
        for _ in range(right - left + 1):
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        
        p0.next.next = cur
        p0.next = pre
        return dummy.next

三、k个一组反转链表

LeetCode 第25题:https://leetcode.cn/problems/reverse-nodes-in-k-group/description/

给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。

k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

Python基础算法——反转链表_第3张图片

class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        n = 0
        cur = head
        while cur:
            n += 1
            cur = cur.next

        dummy = ListNode(next = head)
        p0 = dummy
        pre = None
        cur = p0.next

        while n >= k :
            n -= k
            for _ in range(k):
                tmp = cur.next
                cur.next = pre
                pre = cur
                cur = tmp
        
            tmp = p0.next
            p0.next.next = cur
            p0.next = pre
            p0 = tmp
        return dummy.next

你可能感兴趣的:(算法,python)