Practice · Linked list · 3 of 6

Add Two Numbers Stored as Linked Lists

You are given l1 and l2, two non-empty linked lists that each hold a non-negative integer, one decimal digit per node, with the ones digit first. So [3, 0, 8] is the number 803.

Return the sum of the two numbers as a linked list in the same form. Neither number has leading zeros, except the number 0 itself, which is [0], and the sum mustn't have any either.

The numbers can have up to 100 digits, far more than an ordinary integer holds, so add them digit by digit.

Example 1

Input
l1 = [3, 0, 8], l2 = [9, 4]
Output
[2, 5, 8]
803 + 49 = 852, written ones digit first.

Example 2

Input
l1 = [9, 9], l2 = [1]
Output
[0, 0, 1]
99 + 1 = 100: the last carry becomes a new node.

Constraints

  • Each list holds 1 to 100 nodes.
  • Every node holds a digit from 0 to 9.
  • No list ends in a 0, except the list [0].