-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDetect_Linked_List_Cycle.cpp
54 lines (44 loc) · 1.22 KB
/
Detect_Linked_List_Cycle.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using namespace std;
#include<iostream>
class ListNode{
public:
int value=0;
ListNode *next;
ListNode(int value)
{
this->value=value;
next= nullptr;
}
};
class LinkedListCycle
{
public:
static bool hasCycle(ListNode *head)
{
ListNode *fastpointer=head;
ListNode *slowpointer=head;
while(fastpointer!=nullptr && fastpointer->next !=nullptr)
{
fastpointer=fastpointer->next->next;
slowpointer=slowpointer->next;
if(fastpointer==slowpointer)
{
return true;
}
}
return false;
}
};
int main(int argc, char*argv[])
{
ListNode *head = new ListNode(1);
head->next = new ListNode(1);
head->next=new ListNode(2);
head->next->next=new ListNode(3);
head->next->next->next=new ListNode(4);
head->next->next->next->next =new ListNode(5);
head->next->next->next->next=new ListNode(6);
cout<<"LinkedList has cycle:"<<LinkedListCycle::hasCycle(head)<<endl;
head->next->next->next->next->next= head->next->next;
cout<<"Linked list has cycle:"<< LinkedListCycle ::hasCycle(head);
}