19/39
Part 4 of 7 · Cycles and meeting pointsLearn and do

Where two lists meet

Two lists can share their ending. The question is which node they share first, and the trap is in the word node.

shared = Node(7, Node(3, Node(6)))
# 2 -> 9 -> 7 -> 3 -> 6
a = Node(2, Node(9, shared))
# 5 -> 1 -> 9 -> 7 -> 3 -> 6
b = Node(5, Node(1, Node(9, shared)))
print(a.next.val == b.next.next.val, a.next is b.next.next)
True False

Once two lists share a node, they share everything after it, since that node has only one next. So the picture is a Y, never an X:

The picture is a Y, never an X
a
2
→
9
→
7
→
3
→
6
→None
b
5
→
1
→
9
→
7
→
3
→
6
→None

Green nodes are the same objects in both lists. Each 9 is its own node.

The first shared node is the 7. Not the 9s: a and b each have a 9, but those are two separate nodes that hold equal values. That's what the True False above says.

Compare nodes with is, because equal values can sit on different nodes

The question asks about nodes, and a node is the same node only when it's the same object. In Python that's is: x is y is true only when x and y are one object.

== happens to work on this Node too. A class without its own __eq__ falls back to identity, so == does the same as is.

Comparing .val is the bug. A version that leveled the two lists and compared values returned the 9 from a.

In the editor, write is_shared(a, b): whether two lists that end share a node. It checks the Y, then two lists whose equal values sit on separate nodes.