Description
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
Analysis
题目难度为:medium
这是一道模拟题,只要按照题目要求解答就好,而且所给的链表数据中,所需要进行计算的数的低位存在链表头,高位存在链表尾,这大大简化了计算,按照顺序从链表头开始依次计算就可以了。
考虑更加复杂的情况,如果所给的数据是低位在链表尾,高位在链表头,例如Input: (2 -> 4 -> 3) + (5 -> 6 -> 4),表示243+564=807,Output: 8 -> 0 -> 7 。这种情况下,可以考虑先将链表倒过来,换成(2 <- 4 <- 3) + (5 <- 6 <- 4)再进行计算
Code(c++)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* p1 = new ListNode(0);
ListNode* p2 = new ListNode(0);
p1->next = l1;
p2->next = l2;
int val = 0, carry = 0;
while (p1->next != NULL && p2->next != NULL) {
p1 = p1->next;
p2 = p2->next;
val = p1->val + p2->val + carry;
if (val >= 10) {
carry = val/10;
val = val%10;
} else {
carry = 0;
}
p1->val = val;
}
if (p1->next != NULL && p2->next == NULL) {
p2->next = p1->next;
}
if (p2->next != NULL && p1->next == NULL) {
p1->next = p2->next;
}
while (p1->next != NULL) {
p1 = p1->next;
val = p1->val+carry;
if (val >= 10) {
carry = val/10;
val = val%10;
} else {
carry = 0;
}
p1->val = val;
}
if (carry != 0) {
p1->next = new ListNode(carry);
}
return l1;
}
};