Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
分析
判斷一個鏈表中是否有循環。一種方法是將鏈表指針依次保存在數組中,看下一個節點是否會在數組中出現,另一種方法是用兩個指針,一個前進一步,另一個前進兩步,如果存在循環,兩個指針肯定有重合的時候。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *array[100000];
int num=0;
struct ListNode *p=head;
while(p!=NULL)
{
for(int i=0;i<num;i++)
{
if(p==array[i])
return true;
}
array[num]=p;
num++;
p=p->next;
}
return false;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
if(head==NULL)
return false;
struct ListNode *p1=head,*p2=head->next;
while(p1!=NULL&&p2!=NULL)
{
if(p1==p2)
return true;
p1=p1->next;
if(p2->next!=NULL)
p2=p2->next->next;
else
p2=p2->next;
}
return false;
}