给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点
C语言
方法1:使用p,q两个指针。p总是向前走,每次只走一步。q从头开始走。对每个节点,看p走的步数是否和q一致。
bool hasCycle(struct ListNode *head) {
struct ListNode* cur1=head;
int pos1=0;
while(cur1){
struct ListNode* cur2=head;
int pos2=0;
while(cur2){
if(cur2==cur1){
if(pos1==pos2)
break;
else{
//printf(环的位置在%d\n",pos2);
return true;
}
}
cur2=cur2->next;
pos2++;
}
cur1=cur1->next;
pos1++;
}
return false;
}
方法二:用快慢指针
使用p,q两个指针。p每次向前走一步,q每次向前走两步。正常情况下p!=q;若在某个时刻p==q,则说明存在环。
bool hasCycle(struct ListNode *head) {
struct ListNode* p=head;
struct ListNode* q=head;
while(p!=NULL && q!=NULL && q->next!=NULL){
p=p->next;
if(q->next!=NULL)
q=q->next->next;
if(p==q)
return true;
}
return false;
}