Created
November 16, 2018 04:40
-
-
Save dlgusdn616/5aa489fa2a2b4fef6144215a2281fe64 to your computer and use it in GitHub Desktop.
This file contains 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
class Solution { | |
public: | |
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { | |
int sum = 0; | |
int carrot = 0; | |
bool isHead = true; | |
ListNode* rhead; | |
ListNode* rbefore; | |
while(l1 || l2) { | |
// calculate | |
sum = carrot; | |
if (l1) | |
sum += l1->val; | |
if (l2) | |
sum += l2->val; | |
carrot = 0; | |
if (sum >= 10) { | |
carrot++; | |
sum -= 10; | |
} | |
// create new node | |
ListNode* ln = new ListNode(sum); | |
if (isHead) { | |
rhead = ln; | |
rbefore = rhead; | |
isHead = false; | |
} else { | |
rbefore->next = ln; | |
rbefore = ln; | |
} | |
if (l1) | |
l1 = (l1->next); | |
if (l2) | |
l2 = (l2->next); | |
} | |
if (carrot == 1) { | |
ListNode* ln = new ListNode(1); | |
if (isHead) { | |
rhead = ln; | |
rbefore = rhead; | |
isHead = false; | |
} else { | |
rbefore->next = ln; | |
rbefore = ln; | |
} | |
} | |
return rhead; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment