LeetCode 445. 两数相加 II
原题链接
中等
作者:
bruce
,
2020-12-25 16:34:48
,
所有人可见
,
阅读 387
/**
* 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) {
// 思路就是先写一个翻转链表函数,然后l1和l2翻转,结果相加之后再翻转即可
ListNode *r1 = reverseNode(l1);
ListNode *r2 = reverseNode(l2);
ListNode *dummy = new ListNode(-1), *cur = dummy;
int t = 0;
while(r1 || r2)
{
if(r1) t+=r1->val, r1 = r1->next;
if(r2) t+=r2->val, r2 = r2->next;
cur->next = new ListNode(t%10);
t/=10;
cur = cur->next;
}
if(t) cur->next = new ListNode(t); // 这个地方要考虑最后还有进位,不能漏了
return reverseNode(dummy->next);
}
// 链表的翻转
ListNode*reverseNode(ListNode * head)
{
if(!head || !head->next) return head;
ListNode *a = head, *b = head->next;
while(b)
{
ListNode *c = b->next;
b->next = a;
a = b;
b = c;
}
head->next = NULL;
return a;
}
};