File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ Problem: Detect Cycle in a Linked List
3+
4+ Description:
5+ This program detects if a singly linked list contains a cycle (loop) using
6+ Floyd's Hare and Tortoise algorithm. The algorithm uses two pointers moving
7+ at different speeds. If there is a loop, the two pointers will meet.
8+ */
9+
10+ #include < bits/stdc++.h>
11+ using namespace std ;
12+
13+ class Node {
14+ public:
15+ int data;
16+ Node* next;
17+
18+ Node (int val){
19+ data = val;
20+ next = NULL ;
21+ }
22+ };
23+
24+ class LinkedList {
25+ private:
26+ Node* head;
27+
28+ public:
29+ LinkedList (){
30+ head = NULL ;
31+ }
32+
33+ void insertatend (int val){
34+ Node* newNode = new Node (val);
35+ if (head == NULL ){
36+ head = newNode;
37+ return ;
38+ }
39+ Node* temp = head;
40+ while (temp->next != NULL ){
41+ temp = temp->next ;
42+ }
43+ temp->next = newNode;
44+ }
45+
46+ void createloop (int pos){
47+ if (pos <= 0 ) return ;
48+ Node* temp = head;
49+ Node* loopnode = nullptr ;
50+ int count = 1 ;
51+
52+ while (temp->next ) {
53+ if (count == pos) loopnode = temp;
54+ temp = temp->next ;
55+ count++;
56+ }
57+ temp->next = loopnode;
58+ }
59+
60+ bool hascycle (){
61+ Node* slow = head;
62+ Node* fast = head;
63+
64+ while (fast != NULL && fast->next != NULL ){
65+ slow = slow->next ;
66+ fast = fast->next ->next ;
67+
68+ if (slow == fast){
69+ return true ;
70+ }
71+ }
72+ return false ;
73+ }
74+
75+ void display (){
76+ Node* temp = head;
77+ while (temp != NULL ){
78+ cout << temp->data << " -> " ;
79+ temp = temp->next ;
80+ }
81+ cout << " NULL" << endl;
82+ }
83+
84+
85+ };
86+
87+ int main (){
88+ LinkedList ll;
89+
90+ ll.insertatend (1 );
91+ ll.insertatend (2 );
92+ ll.insertatend (3 );
93+ ll.insertatend (4 );
94+ ll.insertatend (5 );
95+ ll.insertatend (6 );
96+ ll.insertatend (7 );
97+
98+ cout<<" Linked List: " ;
99+ ll.display ();
100+
101+ ll.createloop (3 );
102+
103+ if (ll.hascycle ()){
104+ cout<<" Cycle detected in the linked list" <<endl;
105+ } else {
106+ cout<<" No cycle detected in the linked list" <<endl;
107+ }
108+ }
You can’t perform that action at this time.
0 commit comments