leetCode_Add to List 206. Reverse Linked List

本文详细解析了一道链表逆置的经典算法题,通过对比两种实现方式,剖析了初次尝试出现的问题及其解决方法。

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

总觉得犯得错误低级到不行

这次的题目很简单,给你一个链表的头指针(没有头节点),逆置这个链表,例如把  1->2->3->4 变成 4->3->2->1


拿到题目一看,这还不简单,先找到尾节点,不停的把头结点进行尾插法不就行了(头指针和尾指针相等时就停止),于是代码如下:


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head)
            return head;
        ListNode* rear = NULL,*temporary = NULL;
        temporary = head;
        while(temporary->next){//遍历直到为节点
            temporary = temporary->next;
        }
        rear = temporary;//尾指针指向尾节点
        
        while(head != rear){
            temporary = head;
            

            temporary->next = rear->next;
            
            rear->next = temporary;
            
            head = head->next;
            
        }
        return rear;
    }
};
看起来没什么问题,提交走起

结果:

Line 25: member access within null pointer of type 'struct ListNode'

而会出现这个错误是因为非法访问内存,试图读取NULL的成员,而错误又是在 temporary->next = rear->next;   那一定是temporary在某次被置为了NULL,一直在肉眼debug没找到,后来在本地debug了一遍,结果是在第一次while循环中最后一句  head = head->next 使 head 变为了NULL,第二次试图访问NULL->next这当然是不行的 ,问题找到了,那来看看我为什么会出现这个问题,原因就在 temporary = head;当把head赋给temporary后,它俩就指向了同一个节点,而后面我用temporay去修改节点的next域后,head->next也跟着改变了(开始写的时候竟然妄想他们是独立的)

下面给出修改后的代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head)
            return head;
        ListNode* rear = NULL,*temporary = NULL;
        temporary = head;
        while(temporary->next){
            temporary = temporary->next;
        }
        rear = temporary;
        
        while(head != rear){
            temporary = head->next;
            

            head->next = rear->next;
            
            rear->next = head;
            
            head = temporary;
            
        }
        return rear;
    }
};

有temporary去存head->next,在修改head最后把temporary赋给head就避开这种问题了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值