| 5 | |
| 6 | |
| 7 | class Linked_List: |
| 8 | def __init__(self): |
| 9 | self.head = None |
| 10 | |
| 11 | def Insert_At_End(self, new_data): |
| 12 | new_node = Node(new_data) |
| 13 | if self.head is None: |
| 14 | self.head = new_node |
| 15 | return |
| 16 | current = self.head |
| 17 | while current.next: |
| 18 | current = current.next |
| 19 | current.next = new_node |
| 20 | |
| 21 | def Detect_and_Remove_Loop(self): |
| 22 | slow = fast = self.head |
| 23 | while slow and fast and fast.next: |
| 24 | slow = slow.next |
| 25 | fast = fast.next.next |
| 26 | if slow == fast: |
| 27 | self.Remove_loop(slow) |
| 28 | print("Loop Found") |
| 29 | return 1 |
| 30 | return 0 |
| 31 | |
| 32 | def Remove_loop(self, Loop_node): |
| 33 | ptr1 = self.head |
| 34 | while 1: |
| 35 | ptr2 = Loop_node |
| 36 | while ptr2.next != Loop_node and ptr2.next != ptr1: |
| 37 | ptr2 = ptr2.next |
| 38 | if ptr2.next == ptr1: |
| 39 | break |
| 40 | ptr1 = ptr1.next |
| 41 | ptr2.next = None |
| 42 | |
| 43 | def Display(self): |
| 44 | temp = self.head |
| 45 | while temp: |
| 46 | print(temp.data, "->", end=" ") |
| 47 | temp = temp.next |
| 48 | print("None") |
| 49 | |
| 50 | |
| 51 | if __name__ == "__main__": |