//class ListNode {
// public:
// int value;
// ListNode* next;
// ListNode(int v) : value(v), next(NULL) {}
//};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
// write your solution here
ListNode * p1 = l1;
ListNode * p2 = l2;
ListNode * dummy = new ListNode(0);
ListNode * p3 = dummy;
int curr = 0;
int carry = 0;
while(p1 != nullptr || p2 != nullptr){
if (p1 != nullptr){
curr += p1->value;
p1 = p1->next;
}
if (p2 != nullptr){
curr += p2->value;
p2 = p2->next;
}
curr += carry;
carry = 0;
if (curr > 9){
curr -= 10;
carry = 1;
}
p3->next = new ListNode(curr);
curr = 0;
p3 = p3->next;
}
if (carry == 1){
p3->next = new ListNode(1);
}
return dummy->next;
}
};
Remember to clear curr = 0 after creating a new node...
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.