Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion linked_lists/intersection.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,11 @@ 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
if not headA or not headB:
return None
p1, p2 = headA, headB
while p1.val!= p2.val:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We want to compare the node objects and not just their values. Two nodes can have the same values but be different objects in memory!

Suggested change
while p1.val!= p2.val:
while p1 != p2:

p1 = p1.next if p1.next else headB
p2 = p2.next if p2.next else headA
Comment on lines +18 to +19

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your current code causes an infinite loop in some cases.
If you make this change, what will happen is p1 will become each node in list A, then each node in list B and then get set to None.
p2 will become each node in list B and then each node in list B and get set to None at the same time as p1 gets set to None. Then the while loop condition will become Falsey, and you'll return None.

When you set p1 to p1.next only if p1.next exists (and the equivalent with p2) they never get set to None therefore you end up in an infinite loop.

Try using the debugger on test case 4 test_will_return_none_when_no_intersection to see what happens.

Suggested change
p1 = p1.next if p1.next else headB
p2 = p2.next if p2.next else headA
p1 = p1.next if p1 else headB
p2 = p2.next if p2 else headA
Suggested change
p1 = p1.next if p1.next else headB
p2 = p2.next if p2.next else headA
p1 = p1.next if p1.next else headB
p2 = p2.next if p2.next else headA


return p1