标签:
Given a linked list, determine if it has a cycle in it.
快慢步,直接AC代码:
值得注意一下的地方就是if(!p2->next || !p2->next->next),如果p2==NULL,那么p2->next用法是错误的,而||运算符的性质是当前一个条件为真时,第二个条件不再判断。
bool hasCycle(ListNode *head) { if(!head || !head->next) return false; ListNode *p1= head; ListNode *p2= head; while(p2) { if(!p2->next || !p2->next->next) return false; p2=p2->next->next; p1=p1->next; if(p1==p2) return true; } return false; }
LeetCode【141】Linked List Cycle
标签:
原文地址:http://www.cnblogs.com/ww-jin/p/4487128.html