from Data_structures import Node def loop_checker(head): visited = set() if head is None or head.next is None: raise ValueError("Head or Head.next is None") p = head visited.add(p) p = p.next while (p): if p in visited: return p else: visited.add(p) p = p.next return None if __name__ in '__main__': head = Node(10) head.next = Node(20) cycleNode = Node(40) head.next.next = cycleNode head.next.next.next = Node(50) head.next.next.next.next = Node(53) head.next.next.next.next.next = cycleNode # Can not print linkedList, as there's a cycle # head.printLinkedList() print(loop_checker(head).val)
return pB if pA is pB: return pA visited.add(pA) visited.add(pB) if pA: pA = pA.next if pB: pB = pB.next return None if __name__ in '__main__': # Making A LinkedLIst headA = Node(10) headA.next = Node(20) # Making B LinkedList headB = Node(765) headB.next = Node(543) headB.next.next = Node(432) # Creating Intersecting Node and appendingn to lists intersectNode = Node(40) headA.next.next = intersectNode headB.next.next.next = intersectNode # adding some more fluff nodes headA.next.next.next = Node(50) headA.next.next.next.next = Node(53) headA.printLinkedList() headB.printLinkedList() print(intersection(headA, headB).val)
from Data_structures import Node def loop_checker(head): visited = set() if head is None or head.next is None: raise ValueError("Head or Head.next is None") p = head visited.add(p) p = p.next while(p): if p in visited: return p else: visited.add(p) p = p.next return None if __name__ in '__main__': head = Node(10) head.next = Node(20) cycleNode = Node(40) head.next.next = cycleNode head.next.next.next = Node(50) head.next.next.next.next = Node(53) head.next.next.next.next.next = cycleNode # Can not print linkedList, as there's a cycle # head.printLinkedList() print(loop_checker(head).val)