題目
題解
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode dummy;
ListNode *current=&dummy;
int carry=0;
while(l1||l2||carry){
int sum=carry;
if(l1){
sum+=l1->val;
l1=l1->next;
}
if(l2){
sum+=l2->val;
l2=l2->next;
}
carry=sum/10;
current->next=new ListNode(sum%10);
current=current->next;
}
return dummy.next;
}
};
-
从最低位开始相加(链表头部)
-
处理每一位的 进位
-
若有剩余进位,要在最后加一个节点
| l1.val | l2.val | carry | sum | 新节点值 | 下一位carry |
|---|---|---|---|---|---|
| 2 | 5 | 0 | 7 | 7 | 0 |
| 4 | 6 | 0 | 10 | 0 | 1 |
| 3 | 4 | 1 | 8 | 8 | 0 |