Given a linked list, determine if it has a cycle in it.
简单题,只要知道快慢指针这个技巧就很容易解了。
1 class Solution {
2 public:
3 bool hasCycle(ListNode *
head) {
4 if(head ==
NULL)
5 return false;
6 ListNode* slow=head; ListNode* fast=
head;
7 while(fast->next!=NULL && fast->next->next!=
NULL){
8 fast=fast->next->
next;
9 slow=slow->
next;
10 if(fast ==
slow)
11 return true;
12 }
13 return false;
14 }
15 };
但是要注意几个空指针的判断。
转载于:https://www.cnblogs.com/desp/p/4334103.html
相关资源:JAVA上百实例源码以及开源项目