/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode reverseList(ListNode* head){
if (head == nullptr || head->next == nullptr) return head;
ListNode * newhead = reverseList(head->next);
ListNode * curr = newhead;
while(curr->next != nullptr)
curr = curr->next; // find the last node of the new list
curr->next = head;
head->next = nullptr;
return newhead;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (l1 == nullptr) return l2;
else if (l2 == nullptr) return l1;
ListNode * newl1 = reverseList(l1);
ListNode * newl2 = reverseList(l2);
ListNode * l1ptr = newl1; // store results on l1ptr
ListNode * l2ptr = newl2;
int carry = 0; // store carry
while(l1ptr->next != nullptr && l2ptr->next != nullptr){
if (l1ptr->val + l2ptr->val + carry <= 9){
l1ptr->val += l2ptr->val + carry;
carry = 0;
}
else{
l1ptr->val = (l1ptr->val + l2ptr->val + carry) - 10;
carry = 1;
}
l1ptr = l1ptr->next;
l2ptr = l2ptr->next;
}
// exited while loop. Now we are dealing with the last node of one of the lists (or both)
if (l1ptr->val + l2ptr->val + carry <= 9){
l1ptr->val += l2ptr->val + carry;
carry = 0;
}
else{
l1ptr->val = (l1ptr->val + l2ptr->val + carry) - 10;
carry = 1;
}
if (l1->next == nullptr)
// redirect the last node of newl1 to points to remaining nodes of newl2
l1ptr->next = l2ptr->next;
// start working on the remaining nodes
l1ptr = l1ptr->next;
while(l1ptr != nullptr){
if (l1ptr->val + carry <= 9){
l1ptr->val += carry;
carry = 0;
}
else{
l1ptr->val = (l1ptr->val + carry) - 10;
carry = 1;
}
l1ptr = l1ptr->next;
}
// finished. Nodes stored in the list whose head is newl1;
return reverseList(newl1);
}
};
- Reverse list : note how to find the second to last node!! Use curr->next != nullptr, not curr != nullptr... Or else will find the last node instead...
The algo is :
- First reverse both lists.
The algo is :
- First reverse both lists.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.