Mark As Completed Discussion

To detect whether a linked list contains a cycle, we can use the Floyd's Cycle Detection Algorithm. This algorithm makes use of two pointers, a slow pointer and a fast pointer, to traverse the linked list.

Here is the C++ code to detect a cycle in a linked list:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4// Function to detect a cycle in a linked list
5bool hasCycle(ListNode *head) {
6    if (head == nullptr || head->next == nullptr) {
7        return false;
8    }
9
10    ListNode *slow = head;
11    ListNode *fast = head;
12
13    while (fast != nullptr && fast->next != nullptr) {
14        slow = slow->next;
15        fast = fast->next->next;
16
17        if (slow == fast) {
18            return true;
19        }
20    }
21
22    return false;
23}
24
25int main() {
26
27    // Create a linked list with a cycle
28    ListNode *head = new ListNode(1);
29    ListNode *second = new ListNode(2);
30    ListNode *third = new ListNode(3);
31    ListNode *fourth = new ListNode(4);
32
33    head->next = second;
34    second->next = third;
35    third->next = fourth;
36    fourth->next = second; // cycle
37
38    if (hasCycle(head)) {
39        cout << "The linked list contains a cycle." << endl;
40    } else {
41        cout << "The linked list does not contain a cycle." << endl;
42    }
43
44    return 0;
45}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment