Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:Just go through each digit, keep a previous pointer. Note how we use dummy node here!
ListNode* addTwoNumbers(ListNode *l1, ListNode *l2){
ListNode dummy(0);
ListNode *prev = &dummy;
int add, res = 0;
while(l1 != NULL || l2 != NULL || res > 0){
add = res;
if(l1 != NULL) {add += l1->val; l1 = l1->next;}
if(l2 != NULL) {add += l2->val; l2 = l2->next; }
res = add/10;
prev->next = new ListNode(add%10);
prev = prev->next;
}
prev->next = NULL;
return dummy.next;
}
Output: 7 -> 0 -> 8
思路:Just go through each digit, keep a previous pointer. Note how we use dummy node here!
ListNode* addTwoNumbers(ListNode *l1, ListNode *l2){
ListNode dummy(0);
ListNode *prev = &dummy;
int add, res = 0;
while(l1 != NULL || l2 != NULL || res > 0){
add = res;
if(l1 != NULL) {add += l1->val; l1 = l1->next;}
if(l2 != NULL) {add += l2->val; l2 = l2->next; }
res = add/10;
prev->next = new ListNode(add%10);
prev = prev->next;
}
prev->next = NULL;
return dummy.next;
}
No comments:
Post a Comment