mirror of https://github.com/doocs/leetcode.git
25 lines
663 B
C++
25 lines
663 B
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* dummy = new ListNode(0);
|
|
ListNode* cur = dummy;
|
|
int carry = 0;
|
|
while (l1 || l2 || carry) {
|
|
carry += (!l1 ? 0 : l1->val) + (!l2 ? 0 : l2->val);
|
|
cur->next = new ListNode(carry % 10);
|
|
cur = cur->next;
|
|
carry /= 10;
|
|
l1 = l1 ? l1->next : l1;
|
|
l2 = l2 ? l2->next : l2;
|
|
}
|
|
return dummy->next;
|
|
}
|
|
}; |