leetcode_92 反转链表 II

85 阅读1分钟

要求

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。  

示例 1:

image.png

输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]

示例 2:

输入:head = [5], left = 1, right = 1
输出:[5]

核心代码

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
        
class Solution:
    def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
        m,n = left,right
        if m == n:
            return head
        cnt = 1
        pre_m,pn = None,None
        node = head
        while cnt < n:
            if cnt == m -1:
                pre_m = node
            node,cnt = node.next,cnt + 1
        pn = node
        if pn:
            nextn = pn.next
            pn.next = None
        else:
            nextx = None
        if pre_m is None:
            head = self.reverseList(head)
            newhead = head
            while head.next:
                head = head.next
            head.next = nextn
            return newhead
        else:
            pre_m.next = self.reverseList(pre_m.next)
            newhead = head
            while head.next:
                head = head.next
            head.next = nextn
            return newhead

    def reverseList(self,head):
        if head is None or head.next is None:
            return head
        tmp = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return tmp

image.png

重点问题

解题思路:

这道题的含金量还是非常高的,我们使用首先先要找到要替换的节点的前一个节点和替换的最后一个节点,先将反转后面的链表存储起来,我们对其中从指定left ~ right位置的数据进行反转,在将其拼接回去就行了,比较好的一道题,值得在刷!