class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *head;
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
int b = 0;
head = NULL;
ListNode *curp;
while (l1 || l2) {
int a = 0;
if (l1) {
a += l1->val;
l1 = l1->next;
}
if (l2) {
a += l2->val;
l2 = l2->next;
}
a = a + b;
if (a > 9) {
b = 1;
a = a - 10;
} else {
b = 0;
}
if (head == NULL) {
head = new ListNode(a);
curp = head;
} else {
curp->next = new ListNode(a);
curp = curp->next;
}
}
if (b) {
curp->next = new ListNode(b);
}
return head;
}
};
Add Two Numbers
最新推荐文章于 2024-05-07 14:18:04 发布