Skip to content

Commit ea08efa

Browse files
authored
Create solution.cpp
1 parent 513fea9 commit ea08efa

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

LinkedListCycle/solution.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
bool hasCycle(ListNode *head)
12+
{
13+
// Using Floyd's Cycle-Finding Algorithm
14+
// SEE https://www.geeksforgeeks.org/floyds-cycle-finding-algorithm/
15+
auto slowPtr = head;
16+
auto fastPtr = head;
17+
18+
while (slowPtr != nullptr &&
19+
fastPtr != nullptr &&
20+
fastPtr->next != nullptr) // this extra check needed only for the fast pointer as it will move 2 nodes at a time
21+
{
22+
slowPtr = slowPtr->next;
23+
fastPtr = fastPtr->next->next;
24+
25+
if (slowPtr == fastPtr)
26+
{
27+
// slow pointer and fast pointer point to the same node
28+
// this can only occur at this point if a cycle occured in the linked list
29+
// cycle detected
30+
return true;
31+
}
32+
}
33+
34+
// reached end of linked list
35+
// cycle not detected
36+
return false;
37+
}
38+
};

0 commit comments

Comments
 (0)