Linked List Cycle LeetCode solution in C++

1
class Solution {
2
public:
3
bool hasCycle(ListNode *head) {
4
// if head is NULL then return false;
5
if (head == NULL) return false;
6

7
// making two pointers fast and slow and assignning them to head
8
ListNode *fast = head;
9
ListNode *slow = head;
10

11
// till fast and fast-> next not reaches NULL
12
// we will increment fast by 2 step and slow by 1 step
13
while (fast != NULL && fast->next != NULL) {
14
fast = fast->next->next;
15
slow = slow->next;
16

17
// At the point if fast and slow are at same address
18
// this means linked list has a cycle in it.
19
if (fast == slow) return true;
20
}
21

22
// if traversal reaches to NULL this means no cycle.
23
return false;
24
}
25
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0