How to check whether linked list is circular or not without using extra memory if the head is given
Asked
Active
Viewed 612 times
2
-
If you know the count of the nodes, check the last node value and id is same as current node. – Chidambaram Jul 27 '18 at 10:26
-
Probable duplicate of https://stackoverflow.com/questions/2663115/how-to-detect-a-loop-in-a-linked-list – Jim Mischel Jul 27 '18 at 13:53
1 Answers
1
We can use two pointers here
slow pointer which points to the head.
fast pointer which points to the head as well.
Now slow pointer will traverse the list one by one(slow= slow.next)
while fast pointer will jump one node ahead (fast = fast.next.next)
.
So if they both meet in any position then there is a loop in the linkedlist or if the fast pointer terminates by pointing to the null value, It means there is no loop in the link list.
condition -> if(fast.value == slow.value)
then there is a loop.
you can refer this link for more explanation -> https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/

Nisarg
- 1,631
- 6
- 19
- 31

MUKESH RANA
- 26
- 3