给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
解题思路:快慢指针
bool hasCycle(struct ListNode *head) {
struct ListNode *a =NULL,*b=NULL;
if(head==NULL||head->next==NULL)
return false;
a=head,b=head->next;
while(a!=b){
if(b==NULL||b->next==NULL)
return false;
a=a->next;
b=b->next->next;
}
return true;
}