力扣题解(链表)
作者:
衣介书生 | 来源:发表于
2020-03-02 07:48 被阅读0次
/**
* 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(-1);
ListNode *p = &dummyHead;
int t = 0;
while (l1 || l2 || t != 0) {
if (l1) {
t += l1->val;
l1 = l1->next;
}
if (l2) {
t += l2->val;
l2 = l2->next;
}
p->next = new ListNode(t % 10);
p = p->next;
t /= 10;
}
return dummyHead.next;
}
};
本文标题:力扣题解(链表)
本文链接:https://www.haomeiwen.com/subject/fumukhtx.html
网友评论