leetcode 92: Reverse Linked List II

本文介绍了一种反转链表中指定区间[m, n]的方法。通过递归方式实现,该算法可以高效地完成任务,适用于单链表的数据结构。文章详细解释了如何在不改变链表其余部分的情况下反转特定范围内的节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if(!head||!head->next)
            return head;
        ListNode* rest=NULL;
        ListNode* new_head=NULL;
        ListNode* new_tail=NULL;
        if(m==1)
        {
            new_tail=helper(head,1,n,new_head,rest);
            new_tail->next=rest;
            return new_head;
        }
        ListNode* curr=head;
        for(int i=1;i<m-1;i++)
            curr=curr->next;
        new_tail=helper(curr->next,m,n,new_head,rest);
        new_tail->next=rest;
        curr->next=new_head;
        return head;
    }
    ListNode* helper(ListNode *head, int curr, int n, ListNode*& new_head, ListNode*& rest)
    {
        if(curr==n)
        {
            rest=head->next;
            new_head=head;
            return head;
        }
        ListNode* p=helper(head->next,curr+1,n,new_head,rest);
        p->next=head;
        head->next=NULL;
        return head;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值