From c59d571e5fa697d9a4dc7cc7814169e725684513 Mon Sep 17 00:00:00 2001 From: Huma Hameed Date: Wed, 18 Jan 2023 16:00:44 -0500 Subject: [PATCH] passing all tests --- linked_lists/intersection.py | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/linked_lists/intersection.py b/linked_lists/intersection.py index f07e2ae..58e7fc1 100644 --- a/linked_lists/intersection.py +++ b/linked_lists/intersection.py @@ -6,9 +6,43 @@ def __init__(self, value): self.val = value self.next = None +def len_check(head): + head_len = 0 + + while head: + head_len += 1 + head = head.next + + return head_len + def intersection_node(headA, headB): """ Will return the node at which the two lists intersect. If the two linked lists have no intersection at all, return None. """ - pass \ No newline at end of file + if not headA or not headB: + return None + + headA_len = len_check(headA) + headB_len = len_check(headB) + + if headA_len > headB_len: + move = headA_len - headB_len + while move: + headA = headA.next + move -= 1 + elif headB_len > headA_len: + move = headB_len - headA_len + while move: + headB = headB.next + move -= 1 + + while headA: + if headA != headB: + headA = headA.next + headB = headB.next + elif headA == headB: + node_intersection = headA + return node_intersection + + return None \ No newline at end of file