#include <iostream>
using
namespace
std;
struct
Node
{
int
data;
struct
Node* next;
};
Node* addition(Node* temp1, Node* temp2,
int
size1,
int
size2)
{
Node* newNode =
(
struct
Node*)
malloc
(
sizeof
(
struct
Node));
if
(temp1->next == NULL &&
temp2->next == NULL)
{
newNode->data = (temp1->data +
temp2->data);
newNode->next = NULL;
return
newNode;
}
Node* returnedNode =
(
struct
Node*)
malloc
(
sizeof
(
struct
Node));
if
(size2 == size1)
{
returnedNode = addition(temp1->next, temp2->next,
size1 - 1, size2 - 1);
newNode->data = (temp1->data + temp2->data) +
((returnedNode->data) / 10);
}
else
{
returnedNode = addition(temp1, temp2->next,
size1, size2 - 1);
newNode->data =
(temp2->data) +
((returnedNode->data) / 10);
}
returnedNode->data = (returnedNode->data) % 10;
newNode->next = returnedNode;
return
newNode;
}
struct
Node* addTwoLists(
struct
Node* head1,
struct
Node* head2)
{
struct
Node *temp1,
*temp2, *ans = NULL;
temp1 = head1;
temp2 = head2;
int
size1 = 0, size2 = 0;
while
(temp1 != NULL)
{
temp1 = temp1->next;
size1++;
}
while
(temp2 != NULL)
{
temp2 = temp2->next;
size2++;
}
Node* returnedNode =
(
struct
Node*)
malloc
(
sizeof
(
struct
Node));
if
(size2 > size1)
{
returnedNode = addition(head1, head2,
size1, size2);
}
else
{
returnedNode = addition(head2, head1,
size2, size1);
}
if
(returnedNode->data >= 10)
{
ans = (
struct
Node*)
malloc
(
sizeof
(
struct
Node));
ans->data = (returnedNode->data) / 10;
returnedNode->data = returnedNode->data % 10;
ans->next = returnedNode;
}
else
ans = returnedNode;
return
ans;
}
void
Display(Node* head)
{
if
(head == NULL)
{
return
;
}
while
(head->next != NULL)
{
cout << head->data <<
" -> "
;
head = head->next;
}
cout << head->data << endl;
}
void
push(Node** head_ref,
int
d)
{
Node* new_node =
(
struct
Node*)
malloc
(
sizeof
(
struct
Node));
new_node->data = d;
new_node->next = NULL;
if
(*head_ref == NULL)
{
new_node->next = *head_ref;
*head_ref = new_node;
return
;
}
Node* last = *head_ref;
while
(last->next != NULL &&
last != NULL)
{
last = last->next;
}
last->next = new_node;
return
;
}
int
main()
{
Node* first = NULL;
Node* second = NULL;
Node* sum = NULL;
push(&first, 5);
push(&first, 6);
push(&first, 3);
push(&second, 8);
push(&second, 4);
push(&second, 2);
cout <<
"First List : "
;
Display(first);
cout <<
"Second List : "
;
Display(second);
sum = addTwoLists(first, second);
cout <<
"Sum List : "
;
Display(sum);
return
0;
}