# Find first node of loop in a linked list in python

Python program for Find first node of loop in a linked list. Here problem description and explanation.

``````#  Python 3 program for
#  Find first node of loop in a linked list

def __init__(self, data) :
#  Set node value
self.data = data
self.next = None

class SingleLL :
def __init__(self) :
self.tail = None
self.result = None

def insert(self, value) :
#  Create a new node
else :
self.tail.next = node

self.tail = node

def display(self) :
return

while (temp != None) :
print(temp.data , end = " → ")
#  Visit to next node
temp = temp.next

print("null")

#  Find first loop node in given linked list
def findLoopNode(self, node) :
if (node == None or node.next == None) :
#  When get node in loop
self.result = node
return node

#  Get next node
nextNode = node.next
#  important to control recursion
node.next = None
node.next = self.findLoopNode(nextNode)
return node

#  This method are handles the request the finding loop node
def firstLoopNode(self) :
if (self.tail == None or self.tail.next == None) :
print("Loop not exist")
else :
self.result = None
print("First Loop Node Is : ", self.result.data)

def main() :
sll = SingleLL()
sll.insert(1)
sll.insert(2)
sll.insert(3)
sll.insert(4)
sll.insert(5)
sll.insert(6)
sll.insert(7)
#  1 → 2 → 3 → 4 → 5 → 6 → 7 → null
#  Assume that initial have no loop
sll.display()
#  Test Case 1
#  When no loop
sll.firstLoopNode()
#  Test Case 2
#  When loop exists
#  Create a new loop
sll.firstLoopNode()
#  Create a new loop
sll.firstLoopNode()
#  remove loop
sll.tail.next = None

if __name__ == "__main__": main()``````

Output

``````Linked List
1 → 2 → 3 → 4 → 5 → 6 → 7 → null
Loop not exist
First Loop Node Is :  3
First Loop Node Is :  5``````

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.