How to find the length of a loop in a linked list
Loop in a linked list
A linked list is a commonly used data structure made up of nodes that are interlinked using pointers.
Note: Read more on a linked list here.
A linked list may contain a loop if a node points to another node that comes earlier in the chain. If this happens, an endless loop is created in the linked list.
Finding the length of a loop
We can find the length of a loop in a linked list by finding the point of the loop and then counting the number of nodes until we encounter that node again. In the following code example, we use Floyd's cycle detection algorithm to find the length:
Code
class LinkedList:def __init__(self):self.root = Nonedef findLoopLength(self):slow = self.rootfast = self.rootwhile fast.after and fast.after.after:fast = fast.after.afterslow = slow.afterif slow == fast: # check if the two pointers match to find loop pointcount = 1curr = slow.afterwhile curr != slow: # move through the linked list and keep countingcurr = curr.aftercount += 1return count# if no loop found return 0return 0my_list1 = LinkedList()my_list1.root = Node(3)my_list1.root.after = Node(9)my_list1.root.after.after = Node(13)my_list1.root.after.after.after = Node(12)my_list1.root.after.after.after.after = Node(8)my_list1.root.after.after.after.after.after = Node(15)my_list1.root.after.after.after.after.after.after = my_list1.root.after.afterprint("The length of the loop in list 1 is:", my_list1.findLoopLength())my_list2 = LinkedList()my_list2.root = Node(7)my_list2.root.after = Node(3)my_list2.root.after.after = Node(8)print("The length of the loop in list 2 is:", my_list2.findLoopLength())
Explanation
Lines 5–11: Two variables,
fastandslow, go through the list and find the point of the loop by following Floyd's cycle detection algorithm.Lines 12–17: We create another variable
currthat starts at the loop point and goes through the list, counting the number of nodes till it reaches the loop point again. We then return the number of nodes in a variablecount.Lines 15–29: We create two linked lists, one having a loop and the other without a loop, and then call the function
findLoopLengthto find the length of the loop.
Note: You can read about removing a loop in a linked list here.
Free Resources