/**
* 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 *head = nullptr;
ListNode *tail = nullptr;
ListNode *p = nullptr;
int sum = 0;
int carray = 0;
while (l1 != nullptr && l2 != nullptr) {
sum = l1->val + l2->val + carray;
if (sum >= 10) {
carray = 1;
sum -= 10;
}
else {
carray = 0;
}
p = new ListNode(sum);
if (nullptr == head) {
head = p;
}
else {
tail->next = p;
}
tail = p;
l1 = l1->next;
l2 = l2->next;
}
while (l1 != nullptr) {
sum = l1->val + carray;
if (sum >= 10) {
carray = 1;
sum -= 10;
}
else {
carray = 0;
}
p = new ListNode(sum);
tail->next = p;
tail = p;
l1 = l1->next;
}
while (l2 != nullptr) {
sum = l2->val + carray;
if (sum >= 10) {
carray = 1;
sum -= 10;
}
else {
carray = 0;
}
p = new ListNode(sum);
tail->next = p;
tail = p;
l2 = l2->next;
}
if (carray) {
p = new ListNode(carray);
tail->next = p;
}
return head;
}
};
leetcode两数之和
最新推荐文章于 2024-01-18 22:55:30 发布