Last active
December 18, 2017 07:53
-
-
Save balos1/2d15597d47335d71897460ee29a29cf9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
struct ListNode { | |
int val; | |
ListNode *next; | |
ListNode(int x) : val(x), next(NULL) {} | |
}; | |
/** | |
* Definition for singly-linked list. | |
* struct ListNode { | |
* int val; | |
* ListNode *next; | |
* ListNode(int x) : val(x), next(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { | |
ListNode *l3 = new ListNode(0); | |
ListNode *currentl1 = l1; | |
ListNode *currentl2 = l2; | |
ListNode *currentl3 = l3; | |
int carry = 0; | |
for (int place = 0;; ++place) { | |
int a = currentl1 == nullptr ? 0 : currentl1->val; | |
int b = currentl2 == nullptr ? 0 : currentl2->val; | |
int sum = a + b + carry; | |
carry = (sum > 9) ? 1 : 0; | |
currentl3->val = (sum > 9) ? sum-10 : sum; | |
currentl1 = currentl1 == nullptr ? nullptr : currentl1->next; | |
currentl2 = currentl2 == nullptr ? nullptr : currentl2->next; | |
if (currentl1 != nullptr || currentl2 != nullptr) { | |
currentl3->next = new ListNode(0); | |
currentl3 = currentl3->next; | |
} else if (carry) { | |
currentl3->next = new ListNode(carry); | |
break; | |
} else { | |
break; | |
} | |
} | |
return l3; | |
} | |
}; | |
void printList(ListNode *list) { | |
ListNode *tmp = list; | |
std::cout << "("; | |
while(tmp != nullptr) { | |
std::cout << tmp->val; | |
tmp = tmp->next; | |
if (tmp != nullptr) | |
std::cout << "->"; | |
} | |
std::cout << ")"; | |
} | |
int main () { | |
int num1[3] = {2, 4, 3}; | |
int num2[4] = {5, 6, 4, 1}; | |
ListNode l1(num1[0]); | |
ListNode *tmpl1 = &l1; | |
for (int i = 0; i < 2; ++i) { | |
tmpl1->next = new ListNode(num1[i+1]); | |
tmpl1 = tmpl1->next; | |
} | |
ListNode l2(num2[0]); | |
ListNode *tmpl2 = &l2; | |
for (int i = 0; i < 2; ++i) { | |
tmpl2->next = new ListNode(num2[i+1]); | |
tmpl2 = tmpl2->next; | |
} | |
std::cout << "Input: "; | |
printList(&l1); | |
std::cout << " + "; | |
printList(&l2); | |
std::cout << std::endl; | |
Solution solution; | |
ListNode *result = solution.addTwoNumbers(&l1, &l2); | |
std::cout << "Output: "; | |
printList(result); | |
std::cout << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment