|
题目:判断给定链表中是否有环
解题思路:
1、哈希表标记走过的节点(不符合空间复杂度要求)
2、快慢指针:一个指针走一步,一个指针走两步,如果有环,终会相遇。
代码:
bool hasCycle(struct ListNode* head ) {
// write code here
struct ListNode *p = head;
while((p !=NULL)&&(p->next!=NULL))
{
p=p->next->next;
head=head->next;
if(p==head)
return 1;
}
return 0;
}
华点:
p->next->next 是因为p->next!=NULL,而head的NEXT可能==NULL |