# 2. Add Two Numbers 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. - Example 1: ![](https://i.imgur.com/n7Slltu.png) ``` Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807. ``` - Example 2: ``` Input: l1 = [0], l2 = [0] Output: [0] ``` - Example 3: ``` Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1] ``` - Constraints: ``` The number of nodes in each linked list is in the range [1, 100]. 0 <= Node.val <= 9 It is guaranteed that the list represents a number that does not have leading zeros. ``` ## C ```C= #include <stdlib.h> #include <stdio.h> //2. Add Two Numbers struct ListNode { int val; struct ListNode* next; }; struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode* root = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode* current = root; struct ListNode* NewNode = NULL; int temp, v1, v2, carry = 0; while (l1 || l2) { if (l1) { v1 = l1->val; } else { v1 = 0; } if (l2) { v2 = l2->val; } else { v2 = 0; } temp = v1 + v2 + carry; if (temp > 9) { carry = 1; temp = (temp % 10); } else { carry = 0; } NewNode = (struct ListNode*)malloc(sizeof(struct ListNode)); NewNode->val = temp; current->next = NewNode; current = current->next; if (l1)l1 = l1->next; if (l2)l2 = l2->next; } if (carry == 1) { NewNode = (struct ListNode*)malloc(sizeof(struct ListNode)); NewNode->val = carry; NewNode->next = NULL; current->next = NewNode; } NewNode->next = NULL; current = root->next; free(root); return current; } void main() { //2. Add Two Numbers struct ListNode l1[3]; struct ListNode l2[3]; struct ListNode* ptr = l1; ptr->val = 1; ptr->next = ptr + 1; ptr = ptr->next; ptr->val = 2; ptr->next = ptr + 1; ptr = ptr->next; ptr->val = 3; ptr->next = NULL; ptr = l2; ptr->val = 4; ptr->next = ptr + 1; ptr = ptr->next; ptr->val = 5; ptr->next = ptr + 1; ptr = ptr->next; ptr->val = 6; ptr->next = NULL; struct ListNode* result = addTwoNumbers(l1, l2); printf("["); while (result->next != NULL) { printf("%d",result->val); if(result->next != NULL) printf(","); result = result->next; if (result->next == NULL) { printf("%d", result->val); break; } } printf("]\n"); } ``` ## C++