Skip to content

Commit 3386f70

Browse files
Merge pull request #607 from Kinshu-Learner/ll
feat(Cpp): Detect cycle in Linked List using Floyd's algo
2 parents 9256d5a + ff104bf commit 3386f70

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// Problem Statement: Given the head of a linked list, determine if the linked list has a cycle in it.
2+
// This implementation uses Floyd's Tortoise and Hare algorithm.
3+
4+
#include <iostream>
5+
6+
// Definition for singly-linked list.
7+
struct ListNode {
8+
int val;
9+
ListNode *next;
10+
ListNode(int x) : val(x), next(nullptr) {}
11+
};
12+
13+
class Solution {
14+
public:
15+
bool hasCycle(ListNode *head) {
16+
// Initialize two pointers, slow and fast, to the head of the list.
17+
ListNode* slow = head;
18+
ListNode* fast = head;
19+
20+
// Traverse the list with two pointers.
21+
while (slow && fast && fast->next) {
22+
// Slow pointer moves one step at a time.
23+
slow = slow->next;
24+
// Fast pointer moves two steps at a time.
25+
fast = fast->next->next;
26+
27+
// If the pointers meet, there is a cycle.
28+
if (slow == fast) {
29+
return true;
30+
}
31+
}
32+
33+
// If the loop finishes, fast has reached the end, so no cycle.
34+
return false;
35+
}
36+
};
37+
38+
int main() {
39+
Solution sol;
40+
41+
// Test Case 1: Linked list with a cycle
42+
ListNode* head1 = new ListNode(3);
43+
head1->next = new ListNode(2);
44+
head1->next->next = new ListNode(0);
45+
head1->next->next->next = new ListNode(-4);
46+
head1->next->next->next->next = head1->next; // Create a cycle
47+
48+
bool result1 = sol.hasCycle(head1);
49+
std::cout << "Test Case 1 (with cycle): " << (result1 ? "true" : "false") << std::endl;
50+
51+
// Test Case 2: Linked list without a cycle
52+
ListNode* head2 = new ListNode(1);
53+
head2->next = new ListNode(2);
54+
55+
bool result2 = sol.hasCycle(head2);
56+
std::cout << "Test Case 2 (no cycle): " << (result2 ? "true" : "false") << std::endl;
57+
58+
// Test Case 3: Single node without a cycle
59+
ListNode* head3 = new ListNode(1);
60+
61+
bool result3 = sol.hasCycle(head3);
62+
std::cout << "Test Case 3 (single node): " << (result3 ? "true" : "false") << std::endl;
63+
64+
// Clean up memory for non-cyclic lists to prevent leaks.
65+
// Note: Deleting a cyclic list requires breaking the cycle first.
66+
delete head2->next;
67+
delete head2;
68+
delete head3;
69+
// For head1, proper cleanup is more complex and omitted for this example.
70+
71+
return 0;
72+
}

0 commit comments

Comments
 (0)