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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
To solve this problem, we can traverse the two linked lists simultaneously and add the digits at each position, considering their carry overs.
Here are the step-by-step instructions to solve this problem:
p
and q
, to the heads of the input linked lists representing the two numbers to be added.carry
and sum
, to store the carry over and sum at each position.p
and q
become null. For each node:
num1
to the value of node p
if it exists, otherwise set it to 0.num2
to the value of node q
if it exists, otherwise set it to 0.num1
, num2
, and the carry.p
and q
pointers to their next nodes if they exist.Here is the implementation of the above algorithm in Python:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def addTwoNumbers(l1, l2):
dummy = ListNode(0)
curr = dummy
carry = 0
p = l1
q = l2
while p or q:
num1 = p.val if p else 0
num2 = q.val if q else 0
summ = num1 + num2 + carry
carry = summ // 10
curr.next = ListNode(summ % 10)
curr = curr.next
if p:
p = p.next
if q:
q = q.next
if carry > 0:
curr.next = ListNode(carry)
return dummy.next
The time complexity of this algorithm is O(max(m, n)), where m and n are the lengths of the two input linked lists.