Description:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
确定给出的链表是否是循环链表,不使用额外的空间
算法思路:
用快慢指针法,如果快慢指针相遇了,说明是循环链表
bool hasCycle(struct ListNode *head) {
struct ListNode *fast=head,*slow=head; //定义一个快指针一个慢指针
if(head==NULL)
return false;
while(fast->next!=NULL&&fast->next->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow) //当快指针与慢指针相遇时 说明已经形成了环
/*if(fast->val==slow->val) 这样不好,万一不同的结点有相同的值就出错了 */
return true;
}
return false;
}