Add Two Numbers

Medium Linked List AI round

l1 and l2 are the heads of two singly linked lists. Each holds a whole number of 0 or more, one digit a node, the ones digit first, and a number has no zero at its end: only 0 itself is a single node holding 0.

Add the two numbers.

Return the head of a list that holds the sum the same way: one digit a node, the ones digit first, and no zero at its end unless the sum is 0.

Example 1

Input: l1 = [4,0,8], l2 = [8,6]
Output: [2,7,8]

l1 holds 804 and l2 holds 68, each ones digit first, and 804 + 68 = 872. The ones column makes 12, so 2 stays and 1 is carried into the tens, where 0 + 6 + 1 makes 7.

Example 2

Input: l1 = [6,4], l2 = [7,8]
Output: [3,3,1]

Example 3

Input: l1 = [0], l2 = [3,1]
Output: [3,1]

Constraints

  • 1 ≤ number of nodes in each list ≤ 10⁵
  • 0 ≤ node.val ≤ 9
  • The last node of a list is not 0, unless the list is the single node 0

Watch the explanation

More Linked List

All Linked List problems