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)