Visualize

Pattern visualizer

Add Two Numbers

Storing digits least-significant-first isn't an arbitrary quirk — it's exactly the direction elementary-school addition runs in, so the two lists can be walked together node-by-node with no need to reverse anything first. Each step adds the two current digits plus whatever carried over from the previous step, banking the ones digit into the result and carrying the tens digit forward, exactly like adding on paper right-to-left. A dummy head simplifies building the result list, and the loop keeps going as long as either list still has digits or a carry remains. Animated on: Add two numbers as reversed-digit lists: list1=[2,4,3]→342, list2=[5,6,4]→465, sum=807→result=[7,0,8].

Linked List

step 1 / 6
2
[0]
4
[1]
3
[2]
5
[3]
6
[4]
4
[5]
line 2

Input: list1=[2,4,3] representing 342 (reversed), list2=[5,6,4] representing 465 (reversed). Combined array shows all digits. carry=0 initially. Pointer i=0 for list1 (val2), pointer j=0 for list2 (val5).

Pseudocode
1FUNCTION addTwoNumbers(l1, l2):
2 make a dummy start node; tail = dummy; carry = 0
3 WHILE l1 has nodes or l2 has nodes or carry is not 0:
4 sum = (l1's value, or 0 if none) + (l2's value, or 0 if none) + carry
5 carry = sum divided by 10, rounded down
6 attach a new node holding (sum mod 10) after tail
7 tail = the node after tail
8 if l1 has nodes, move l1 to the next node
9 if l2 has nodes, move l2 to the next node
10 END WHILE
11 RETURN the node after dummy
12END FUNCTION

← / → step · space play · Home restart

Where to practice Linked List