题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//这题我不知道大佬们是怎么做的,我这个答案居然过了(苦笑)
class Solution {
public:
bool hasCycle(ListNode *head) {
int sum=0;//题目中说了n的范围是0到10000,所以如果循环次数大于10000是不是说明一定有环,反之如果循环到一定次数结束了说明一定无环
while(head)
{
head=head->next;
sum++;
if(sum>10000)
return true;
}
return false;
}
};
查看3道真题和解析