awelgorithms

Walk two list pointers in lockstep

Updated

p = headA, q = headB. Each round: read p.val and q.val, then p = p.next and q = q.next. Stop when either is null unless you need the leftover suffix.

What to focus on

Both pointers take one next per round. The gap between them stays 0. After the loop, at most one list still has nodes.

Worked examples

equal length

a = [4, 1, 9] as 4→1→9, b = [4, 7, 9] as 4→7→9
  1. pairs (4,4), (1,7), (9,9)
  2. both null

Result: three lockstep rounds

b shorter

a = [4, 1, 9] as 4→1→9, b = [4, 7] as 4→7
  1. pairs (4,4), (1,7)
  2. q null, p at 9

Result: leftover 9 on a

compare equal

a = [4, 1, 9] as 4→1→9, b = [4, 1, 9] as 4→1→9
  1. 4==4, 1==1, 9==9
  2. both null

Result: lists equal

Try it

Write zipWalk(a, b). a is the head of the first list. b is the head of the second list. Each step follows .next on both. Print each pair and any leftover node. Return nothing. On 4→1→9 vs 4→7→9, vs 4→7, and vs 4→1→9.

Both lists are nonempty.