diff --git a/README.md b/README.md index 18e0461..6d970a3 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ The following two linked lists do _not_ intersect at all because while the node `linked_list_b: 1 -> 2 -> 5 -> 4 -> 3` -Thereare no cycles anywhere in the linked list structures. Assume any intersection includes the tails of each list. +There are no cycles anywhere in the linked list structures. Assume any intersection includes the tails of each list. The linked lists must retain their original structure after the function returns. diff --git a/linked_lists/intersection.py b/linked_lists/intersection.py index f07e2ae..55b782c 100644 --- a/linked_lists/intersection.py +++ b/linked_lists/intersection.py @@ -1,6 +1,9 @@ +from email.errors import HeaderParseError + + class Node: def __init__(self, value): self.val = value @@ -9,6 +12,33 @@ def __init__(self, value): def intersection_node(headA, headB): """ Will return the node at which the two lists intersect. + --> pointing TO THE SAME REFERENCE IN MEMORY If the two linked lists have no intersection at all, return None. """ - pass \ No newline at end of file +# ''' create an empty variable to maintain the first seqential digit''' + first = None + current_a = headA + current_b = headB + + while headA and headB: +# '''check to see if current_a is equal to current_b:''' + if current_a is None and current_b is not None: + current_a = headA + current_b = current_b.next + if current_b is None and current_a is not None: + current_b = headB + current_a = current_a.next + while current_a != current_b: + current_a = current_a.next + current_b = current_b.next + # return first + # '''set the empty variable to first same node value''' + if current_a == current_b: + first = current_a + return first + + elif current_a != current_b: + return first + else: + return first + diff --git a/tests/test_intersection.py b/tests/test_intersection.py index aa0937e..97ed296 100644 --- a/tests/test_intersection.py +++ b/tests/test_intersection.py @@ -151,4 +151,32 @@ def test_will_return_none_nodes_have_same_value_different_reference(): answer = intersection_node(head_a, head_b) #Assert - assert answer is None \ No newline at end of file + assert answer is None + + + ## create a test case to chek if the end of the linked lists are the same value + '''Assume any intersection includes the tails of each list.''' + +def test_will_return_tail_if_tail_intersection(): + #arrange + node_d1 = Node("D") + node_q1 = Node("Q") + node_f1 = Node("F") + + node_c1 = Node("C") + node_s1 = Node("S") + node_f1 = Node("F") + #List A: [d, q, f1] + node_d1.next = node_q1 + node_q1.next = node_f1 + + #List B: [c, s, f1] + node_c1.next = node_s1 + node_s1.next = node_f1 + + head_a = node_d1 + head_b = node_c1 + #act + answer = intersection_node(head_a, head_b) + #assert + assert answer == node_f1 \ No newline at end of file