Skip to content

Instantly share code, notes, and snippets.

@dlgusdn616
Created November 16, 2018 04:40
Show Gist options
  • Save dlgusdn616/5aa489fa2a2b4fef6144215a2281fe64 to your computer and use it in GitHub Desktop.
Save dlgusdn616/5aa489fa2a2b4fef6144215a2281fe64 to your computer and use it in GitHub Desktop.
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