背景:LeetCode - 2. Add Two Numbers
描述:
给你两个不为空的链表,而且链表中的数字是反序的,现在要你求出这两个链表所代表的数字的和,同样用链表表示。
链表的定义:
// 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 *ret = l1, *pre = l1;
int up = 0;
while (l1 != NULL && l2 != NULL) {
l1->val = l1->val + l2->val + up;
up = l1->val / 10;
l1->val %= 10;
pre = l1;
l1 = l1->next;
l2 = l2->next;
}
if (l1 == NULL)
pre->next = l2;
l1 = pre->next;
while (l1 != NULL) {
l1->val = l1->val + up;
up = l1->val / 10;
l1->val %= 10;
pre = l1;
l1 = l1->next;
}
if (up != 0) {
ListNode *tmp = new ListNode(up);
pre->next = tmp;
}
return ret;
}
};