题解 | #链表内指定区间反转#

链表内指定区间反转

https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def reverseBetween(self, head, m, n):
        if not head or m == n:
            return head
        
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy
        
        # Move `pre` to the element right before the reversal starts
        for _ in range(m - 1):
            pre = pre.next
        
        # Reverse the sublist from m to n
        reverse = None
        curr = pre.next
        for _ in range(n - m + 1):
            next_temp = curr.next
            curr.next = reverse
            reverse = curr
            curr = next_temp
        
        # Connect the end of the reversed sublist to the remaining part of the list
        pre.next.next = curr
        # Connect the start of the reversed sublist to the initial part of the list
        pre.next = reverse
        
        return dummy.next

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务