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:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
题意大概就是:有两个链表,每个链表从头节点的每一位从低到高代表一个整数,计算这个两个整数的和。
Runtime: 24 ms, faster than 99.98% of C++ online submissions for Add Two Numbers.
Memory Usage: 9.8 MB, less than 100.00% of C++ online submissions for Add Two Numbers.
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *hold_l1 = l1;
ListNode *hold_l2 = l2;
while (l1 != nullptr || l2 != nullptr) { //将l1和l2的每位相加
l1->val += l2->val;
if (l2->next == nullptr) { //如果l2比较短,那么直接跳出循环,去处理l1
break;
}
l2 = l2->next;
if (l1->next == nullptr) { //如果l1比较短,那么将l2长出的部分接到l1后面
l1->next = l2;
break;
}
l1 = l1->next;
}
l1 = hold_l1;
while (l1 != nullptr) { //处理l1,如果值大于10,那么需要进为1给后一位
if (l1->val >= 10) {
l1->val -= 10;
if (l1->next == nullptr) { //如果到了l1的末尾,并且还有一个进为的话,需要开辟一个新节点作为新的末尾
l1->next = hold_l2;
hold_l2->val = 1;
hold_l2->next = nullptr;
} else {
l1->next->val += 1;
}
}
l1 = l1->next;
}
return hold_l1;
}