Skip to content

Instantly share code, notes, and snippets.

@T2hhbmEK
Created September 25, 2015 18:44
Show Gist options
  • Save T2hhbmEK/28e87b193ca112c2faa0 to your computer and use it in GitHub Desktop.
Save T2hhbmEK/28e87b193ca112c2faa0 to your computer and use it in GitHub Desktop.
Add Two Numbers
/**
* 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