141. 环形链表 LeetCode报错:runtime error: member access within null pointer of type 'struct ListNode'...

原文链接: http://www.cnblogs.com/SuzanneHuang/p/10454155.html
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         if(!head->next||!head)
13             return false;
14      ListNode *pre=NULL,* cur=head;
15         
16         while(cur)
17         {
18             ListNode* tmp=cur->next;
19             cur->next=pre;
20             pre=cur;
21             cur=tmp;
22         }
23         return (pre==head);
24     }
25 };

这是出错代码,后来查找原因发现是第12行的空指针判断顺序有问题,应该为if(!head||!head->next)

转载于:https://www.cnblogs.com/SuzanneHuang/p/10454155.html

猜你喜欢

转载自blog.csdn.net/weixin_30500289/article/details/94812670