#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
int val;
struct ListNode *next;
};
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode *t1 = l1, *t2 = l2;
struct ListNode *result = NULL, *t3 = NULL;
int carry = 0;
int i = 0;
while (t1 && t2)
{
struct ListNode *temp = (struct ListNode*)malloc(sizeof(struct ListNode));
temp->next = NULL;
int sum = t1->val + t2->val + carry;
carry = sum / 10;
temp->val = sum % 10;
t1 = t1->next;
t2 = t2->next;
if (!result)
{
result = temp;
t3 = result;
continue;
}
t3->next = temp;
t3 = temp;
}
if (!t1)
{
t1 = t2;
}
while (t1)
{
if (!t3)
{
t3 = (struct ListNode*)malloc(sizeof(struct ListNode));
t3->next = NULL;
}
int sum = t1->val + carry;
carry = sum / 10;
t3->val = sum % 10;
t1 = t1->next;
t3 = t3->next;
}
return result;
}
int main()
{
struct ListNode *l1 = NULL, *l2 = NULL, *t1 = NULL, *t2 = NULL, *result = NULL;
int l1i[] = {2, 4, 3};
int l2i[] = {5, 6, 4};
l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->val = l1i[0];
l1->next = t1;
t1 = NULL;
printf("%d\t", l1->val);
for (int i = 1; i < 3; i++)
{
if (!t1)
{
t1 = (struct ListNode*)malloc(sizeof(struct ListNode));
t1->val = l1i[i];
t1->next = NULL;
}
printf("%d\t", t1->val);
}
printf("\n");
l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->val = l2i[0];
l2->next = t2;
t2 = NULL;
printf("%d\t", l2->val);
for (int i = 1; i < 3; i++)
{
if (!t2)
{
t2 = (struct ListNode*)malloc(sizeof(struct ListNode));
t2->val = l2i[i];
t2->next = NULL;
}
printf("%d\t", t2->val);
}
printf("\n");
result = addTwoNumbers(l1, l2);
t1 = result;
while (t1)
{
printf("%d\t", t1->val);
t1 = t1->next;
}
printf("\n");
while (l1)
{
t1 = l1->next;
free(l1);
l1 = t1;
}
while (l2)
{
t2 = l2->next;
free(l2);
l2 = t2;
}
while (result)
{
t1 = result->next;
free(result);
result = t1;
}
}
The program is suppose to add the values of 2 linked list and store it in a 3rd linked list. The above program compiles but the output list only contains single element. Am I missing something here.
I think the way I am storing and going to the next element of the linked list is the problem.