In the Leetcode Add Two Numbers problem solution in C programming You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Leetcode Add Two Numbers problem solution in C programming
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int carry = 0, sum;
struct ListNode *result = (struct ListNode*) malloc(sizeof(struct ListNode));
struct ListNode *current = result;
struct ListNode *new;
result->val = 0;
result->next = NULL;
if (!l1 && !l2) {
goto end;
}
while (true) {
sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
current->val = sum % 10;
carry = sum >= 10 ? 1 : 0;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
if (!l1 && !l2 && !carry) {
break;
}
new = (struct ListNode*) malloc(sizeof(struct ListNode));
new->next = NULL;
current->next = new;
current = new;
}
end:
return result;
}
Also read,
- Leetcode Add Two Numbers problem solution in C++
- Leetcode Add Two Numbers problem solution in Java
- Leetcode Add Two Numbers problem solution in Python
- Leetcode Add Two Numbers problem solution in C#