Created
September 25, 2015 18:44
-
-
Save T2hhbmEK/28e87b193ca112c2faa0 to your computer and use it in GitHub Desktop.
Add Two Numbers
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
/** | |
* Definition for singly-linked list. | |
* struct ListNode { | |
* int val; | |
* struct ListNode *next; | |
* }; | |
*/ | |
typedef struct ListNode ListNode; | |
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { | |
ListNode *l1cur, *l2cur, *ans, **anscur; | |
int a, b, sum, carry; | |
l1cur = l1; | |
l2cur = l2; | |
ans = NULL; | |
anscur = &ans; | |
carry = 0; | |
while (l1cur != NULL || l2cur != NULL || carry != 0) { | |
if (l1cur != NULL) { | |
a = l1cur->val; | |
l1cur = l1cur->next; | |
} | |
else { | |
a = 0; | |
} | |
if (l2cur != NULL) { | |
b = l2cur->val; | |
l2cur = l2cur->next; | |
} | |
else { | |
b = 0; | |
} | |
sum = a + b + carry; | |
carry = sum >= 10; | |
sum = carry ? sum - 10 : sum; | |
(*anscur) = (ListNode*)malloc(sizeof(ListNode)); | |
(*anscur)->val = sum; | |
(*anscur)->next = NULL; | |
anscur = &((*anscur)->next); | |
} | |
return ans; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment