Created
January 29, 2016 15:20
-
-
Save shanehou/a1617d71a21d688fdd18 to your computer and use it in GitHub Desktop.
Add Two Numbers
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
/** | |
* Definition for singly-linked list. | |
* struct ListNode { | |
* int val; | |
* struct ListNode *next; | |
* }; | |
*/ | |
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { | |
if (!l1) return l2; | |
if (!l2) return l1; | |
int carry = 0; | |
struct ListNode* root = malloc(sizeof(struct ListNode*)); | |
struct ListNode* node = root; | |
while (l1 || l2) { | |
if (!l1 && carry == 0) { | |
node->next = l2; | |
break; | |
} | |
if (!l2 && carry == 0) { | |
node->next = l1; | |
break; | |
} | |
int sum = carry; | |
if (l1) { | |
sum += l1->val; | |
l1 = l1->next; | |
} | |
if (l2) { | |
sum += l2->val; | |
l2 = l2->next; | |
} | |
carry = sum / 10; | |
struct ListNode* newNode = malloc(sizeof(struct ListNode*)); | |
newNode->val = sum % 10; | |
node->next = newNode; | |
node = newNode; | |
} | |
if (carry > 0) { | |
struct ListNode* newNode = malloc(sizeof(struct ListNode*)); | |
newNode->val = carry; | |
node->next = newNode; | |
} | |
return root->next; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment