leetcode--Reverse Linked List II

本文详细介绍了如何使用头插法变形来实现C++单链表中指定区间的元素反转,包括边界条件处理和优化措施。通过实例分析,展示了算法的具体实现过程,并指出了一个常见的错误陷阱,即在条件判断中使用了错误的逻辑表达式。

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

1.题目描述

Reverse a linked list from position m to n. Do it in-place and in one-pass.
 
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
 
return 1->4->3->2->5->NULL.
 
Note:
Given m, n satisfy the following condition:
1 ? m ? n ? length of list.

2.解法分析

解法就是头插法的变形,稍微改动一下,确定一下边界条件就好了。

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        if(m>=n)return head;
        if(!head)return NULL;
        
        int count=1;
        ListNode * cur=head;
        ListNode * start=NULL;
        ListNode * headPrev=NULL;
        while(count<m&&cur)
        {
            headPrev=cur;
            cur=cur->next;count++;
        }
        
        start=cur;
        while(count<n&&cur->next)
        {
            ListNode *temp = cur->next;
            cur->next=temp->next;
            temp->next=start;
            start=temp;
            if(headPrev)headPrev->next=start;
            count++;
        }
        
        if(headPrev)return head;
        else return start;
        
    }
};

 

这个题目很简单,但是我在上面竟然磨叽了一个小时,伤不起,究其原因,主要是两个while循环的判断条件打错了,写的条件和我脑海中想象的不一样,是这样的:

我本意是while(count<m&&cur)却写成了while(count<m&&!cur),好吧,我决定以后写这种判断条件尽量写成cur!=NULL,免得出这种哭笑不得的错误。

转载于:https://www.cnblogs.com/obama/p/3266083.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值