You are on page 1of 3

// Online C compiler to run C program online

#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *start = NULL;
struct node *create_ll(struct node* start);
struct node *display(struct node* start);
//struct node *insert_after(struct node *start);
struct node *add(struct node *l1, struct node *l2);
int main() {
struct node *l1=NULL, *l2=NULL;
l1=create_ll(l1);
printf("Linked list 1: ");
l1= display(l1);
printf("\n");
l2=create_ll(l2);
printf("Linked list 2: ");
l2= display(l2);
struct node *ans;
ans=add(l1,l2);
printf("\nSum: ");
ans=display(ans);
return 0;
}
struct node *create_ll(struct node *start)
{
struct node *ptr, *new_node;
int num;
printf("Enter data: ");
scanf("%d", &num);
while(num!=-1)
{
new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = num;
if(start==NULL)
{
new_node->next=NULL;
start=new_node;
}
else
{
ptr=start;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=new_node;
new_node->next=NULL;
}
printf("Enter data: ");
scanf("%d",&num);
}
return start;
}
struct node *display(struct node *start)
{
struct node *ptr;
ptr=start;
while(ptr!=NULL)
{
printf(" \t%d", ptr->data);
ptr=ptr->next;
}
return start;
}
struct node *add(struct node *l1, struct node *l2)
{
int i=0;
struct node *add12=NULL, *new_node, *ptr;
while(l1!=NULL&&l2!=NULL)
{
new_node=(struct node*)malloc(sizeof(struct node));
new_node->data=l1->data+l2->data+i;
if(new_node->data>=10)
{
new_node->data=(new_node->data)%10;
i=1;
}
else i=0;
if(add12==NULL)
{
new_node->next=NULL;
add12=new_node;
}
else
{
ptr=add12;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=new_node;
new_node->next=NULL;
}
l1=l1->next;
l2=l2->next;
}
struct node *temp;
if(l1==NULL) temp = l2;
else if(l2==NULL) temp = l1;
while(temp!=NULL)
{
new_node=(struct node*)malloc(sizeof(struct node));
new_node->data=temp->data+i;
if(new_node->data>=10)
{
new_node->data=(new_node->data)%10;
i=1;
}
else i = 0;
if(add12==NULL)
{
new_node->next=NULL;
add12=new_node;
}
else
{
ptr=add12;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=new_node;
new_node->next=NULL;
}
temp=temp->next;
}
if(i)
{
ptr=add12;
new_node=(struct node*)malloc(sizeof(struct node));
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=new_node;

new_node->data=1;
new_node->next=NULL;
}
return add12;
}

You might also like