leetCode_Add to List 206. Reverse Linked List

来源:互联网 发布:用手机开淘宝店的步骤 编辑:程序博客网 时间:2024/06/05 11:09

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

这次的题目很简单,给你一个链表的头指针(没有头节点),逆置这个链表,例如把  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就避开这种问题了。


原创粉丝点击