Problem
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 contain 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:
1 |
|
Explanation
-
First create a ListNode with value equals to
(l1.val + l2.val)%10
, and initialize the carry be(l1.val + l2.val)/10
. Also, we need a pointer to point to the last node of the result ListNode. -
While
l1
orl2
is notNULL
, getl1
’s value andl2
’s value, sum them up plus carry, module 10 to be the next node’s value, update the pointer of the result ListNode and updatel1
andl2
to be their next node. -
Outside of the while loop, when both
l1
andl2
are null, if the carry is not zero, we create a node of the carry’s value and append to the result ListNode.
Solution
1 |
|