class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
// write your code here
if(l1 == NULL){
return l2;
}
if(l2 == NULL){
return l1;
}
l1 = reverse(l1);
l2 = reverse(l2);
int carry = 0;
ListNode *head = new ListNode(0);
ListNode *dummy = head;
while(1){
if(l1!=NULL){
carry += l1->val;
l1 = l1->next;
}
if(l2!=NULL){
carry += l2->val;
l2 = l2->next;
}
head->next = new ListNode(carry%10);
carry = carry/10;
if(carry!=0 || l1!=NULL || l2!=NULL){
head = head->next;
}
else{
break;
}
}
dummy->next = reverse(dummy->next);
return dummy->next;
}
ListNode* reverse(ListNode *head){
ListNode* prev = NULL;
ListNode* cur = head;
ListNode* temp;
while(cur!=NULL){
temp = cur->next;
cur->next = prev;
prev = cur;
cur = temp;
}
return prev;
}
};
445. Add Two Numbers II
最新推荐文章于 2021-11-30 22:59:53 发布