Leetcode - 两数相加
程序员文章站
2022-06-17 19:49:22
...
解题思路:(Cpp)
直接上代码。
/**
* 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* dummyHead = new ListNode(0);
ListNode* curr = dummyHead;
int carry = 0;
int sum;
while (l1 || l2){
sum = 0;
if (l1){
sum += l1->val;
l1 = l1->next;
}
if (l2){
sum += l2->val;
l2 = l2->next;
}
sum += carry;
carry = sum / 10;
curr->next = new ListNode(sum % 10);
curr = curr->next;
}
if (carry > 0)
curr->next = new ListNode(carry);
return dummyHead->next;
}
};