You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
Explanation: 3427 + 465 = 3892
Here's a step-by-step explanation of how to solve the problem:
addTwoNumbers
that takes two linked lists l1
and l2
as input.carry
and dummyHead
with value 0
and ListNode(0)
, respectively.current
to dummyHead
.l1
or l2
or carry
is not empty, adhere to the following steps:
l1
is not empty, update l1
's value and move to the next node.l2
is not empty, update l2
's value and move to the next node.carry
and update current
's next node to ListNode(sum % 10)
.current
and set carry
to the integer division of sum
by 10.dummyHead
's next node, which will hold the head of the resulting linked list.This algorithm iterates through the input linked lists in a single pass, updating the current
variable to construct the result linked list while considering carryovers. The time complexity of this algorithm is O(n), where n is the length of the longer input list.