Ans. To check if a given linked list contains a cycle, we can use Floyd's cycle-finding algorithm, also known as the "tortoise and hare" algorithm. This algorithm uses two pointers, a slow pointer, and a fast pointer, to traverse the linked list.
Here is the approach to detecting a cycle in a linked list:
- Initialize two pointers, slow and fast, pointing to the head of the linked list.
- Move the slow pointer one step at a time and the fast pointer two steps at a time.
- If the fast pointer encounters a null node, it means there is no cycle in the linked list, so we can return false.
- If the fast pointer and the slow pointer meet at some point, it indicates the presence of a cycle in the linked list.
- To find the starting node of the cycle, reset the slow pointer to the head of the linked list and keep the fast pointer at the meeting point.
- Move both pointers one step at a time until they meet again. The node at which they meet will be the starting node of the cycle.
Here's the C++ implementation:
I2luY2x1ZGUgPGlvc3RyZWFtPgoKc3RydWN0IExpc3ROb2RlIHsKaW50IHZhbDsKTGlzdE5vZGUqIG5leHQ7Ckxpc3ROb2RlKGludCB2YWx1ZSkgOiB2YWwodmFsdWUpLCBuZXh0KG51bGxwdHIpIHt9Cn07Cgpib29sIGhhc0N5Y2xlKExpc3ROb2RlKiBoZWFkKSB7CmlmIChoZWFkID09IG51bGxwdHIgfHwgaGVhZC0+bmV4dCA9PSBudWxscHRyKSB7CnJldHVybiBmYWxzZTsKfQoKTGlzdE5vZGUqIHNsb3cgPSBoZWFkOwpMaXN0Tm9kZSogZmFzdCA9IGhlYWQ7Cgp3aGlsZSAoZmFzdCAhPSBudWxscHRyICYmIGZhc3QtPm5leHQgIT0gbnVsbHB0cikgewpzbG93ID0gc2xvdy0+bmV4dDsKZmFzdCA9IGZhc3QtPm5leHQtPm5leHQ7CgppZiAoc2xvdyA9PSBmYXN0KSB7CnJldHVybiB0cnVlOwp9Cn0KCnJldHVybiBmYWxzZTsKfQoKTGlzdE5vZGUqIGZpbmRDeWNsZVN0YXJ0KExpc3ROb2RlKiBoZWFkKSB7CmlmIChoZWFkID09IG51bGxwdHIgfHwgaGVhZC0+bmV4dCA9PSBudWxscHRyKSB7CnJldHVybiBudWxscHRyOwp9CgpMaXN0Tm9kZSogc2xvdyA9IGhlYWQ7Ckxpc3ROb2RlKiBmYXN0ID0gaGVhZDsKYm9vbCBoYXNDeWNsZSA9IGZhbHNlOwoKd2hpbGUgKGZhc3QgIT0gbnVsbHB0ciAmJiBmYXN0LT5uZXh0ICE9IG51bGxwdHIpIHsKc2xvdyA9IHNsb3ctPm5leHQ7CmZhc3QgPSBmYXN0LT5uZXh0LT5uZXh0OwoKaWYgKHNsb3cgPT0gZmFzdCkgewpoYXNDeWNsZSA9IHRydWU7CmJyZWFrOwp9Cn0KCmlmICghaGFzQ3ljbGUpIHsKcmV0dXJuIG51bGxwdHI7Cn0KCnNsb3cgPSBoZWFkOwp3aGlsZSAoc2xvdyAhPSBmYXN0KSB7CnNsb3cgPSBzbG93LT5uZXh0OwpmYXN0ID0gZmFzdC0+bmV4dDsKfQoKcmV0dXJuIHNsb3c7Cn0=
The function checks whether a given linked list contains a cycle using Floyd's cycle-finding algorithm. It returns if a cycle is found and otherwise.
The function finds the starting node of the cycle in a linked list. It first uses Floyd's algorithm to determine if a cycle exists. If a cycle is found, it resets the slow pointer to the head and moves both pointers one step at a time until they meet again at the starting node of the cycle. Finally, it returns the starting node or if no cycle is present.
You can use these functions to check for a cycle in a linked list and find the starting node if a cycle exists.
Comments
Add comment