Detect a cycle in a linked list.
Example 1:
Input:
given in question
Output: The linked list has a cycle.
Example 2:
Input:
According to question
Output: The linked list does not have a cycle.
1. Linked List Representation:-
The code defines a linked list using a Node structure. Each node has an integer data value (int data) and a
pointer to the next node (Node* next).
2. hasCycle Function:-
The hasCycle function is responsible for detecting a cycle in the linked list. It takes the head of the
linked list as an argument.
3. Initialization:-
Inside the hasCycle function, two pointers slow and fast are initialized to the head of the linked list.
These two pointers will traverse the list at different speeds to detect a cycle.
4. Cycle Detection Loop:-
A while loop is used to iterate through the list. The loop continues as long as both fast and fast->next are
not nullptr.
In each iteration, the slow pointer moves one step forward (slow = slow->next), and the fast pointer moves
two steps forward (fast = fast->next->next).
5. Cycle Detection condition:-
Within the loop, there is a conditional check: if (slow == fast). This check is used to determine if the two
pointers have met or overlapped.
If the pointers meet, it means that a cycle has been detected in the linked list, and the function returns
true.
6. Returning the Result:-
If the loop completes without detecting a cycle, the function returns false, indicating that no cycle exists
in the linked list.
7. Main Function:-
In the main function, a sample linked list is created with four nodes. The fourth node is connected back to
the second node, creating a cycle.
8. Output:-
The hasCycle function is called to detect the cycle, and the result is printed. If a cycle is detected, it
prints "The linked list has a cycle." If no cycle is detected, it prints "The linked list does not have a
cycle."