Created
October 23, 2019 23:21
-
-
Save studentbrad/25969bf815076a0b2f0b25d009d44d63 to your computer and use it in GitHub Desktop.
Add two linked lists representing a non-negative number
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
struct ListNode *linked_addition(struct ListNode *l1, struct ListNode *l2) | |
{ | |
struct ListNode *l1Start = l1; | |
struct ListNode *l2Start = l2; | |
struct ListNode *lSum = (struct ListNode *)malloc(sizeof(struct ListNode)); | |
struct ListNode *lSumStart = lSum; | |
bool flag = true; | |
while (flag) | |
{ | |
lSum->val = l1->val + l2->val; | |
if (l1->next && l2->next) | |
{ | |
l1 = l1->next; | |
l2 = l2->next; | |
lSum->next = (struct ListNode *)malloc(sizeof(struct ListNode)); | |
lSum = lSum->next; | |
lSum->next = NULL; | |
flag = true; | |
} | |
else | |
{ | |
lSum->next = NULL; | |
flag = false; | |
} | |
} | |
while (l1->next || l2->next) | |
{ | |
if (l1->next) | |
{ | |
l1 = l1->next; | |
lSum->next = (struct ListNode *)malloc(sizeof(struct ListNode)); | |
lSum = lSum->next; | |
lSum->next = NULL; | |
lSum->val = l1->val; | |
} | |
if (l2->next) | |
{ | |
l2 = l2->next; | |
lSum->next = (struct ListNode *)malloc(sizeof(struct ListNode)); | |
lSum = lSum->next; | |
lSum->next = NULL; | |
lSum->val = l2->val; | |
} | |
} | |
l1 = l1Start; | |
l2 = l2Start; | |
lSum = lSumStart; | |
flag = true; | |
int carry = 0; | |
while (flag) | |
{ | |
lSum-> val += carry; | |
if(lSum->val >= 10) | |
{ | |
carry = 1; | |
lSum->val %= 10; | |
} | |
else carry = 0; | |
if (lSum->next) lSum = lSum->next; | |
else flag = false; | |
} | |
if (carry) | |
{ | |
lSum->next = (struct ListNode *)malloc(sizeof(struct ListNode)); | |
lSum = lSum->next; | |
lSum->next = NULL; | |
lSum->val = carry; | |
carry = 0; | |
} | |
lSum = lSumStart; | |
return lSum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment