Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.3 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node* link;
};

struct node* add_node(struct node* head , int val)
{
    struct node* newnode =(struct node *) malloc(sizeof(struct node));
    newnode->data = val;
    newnode->link = NULL;
    newnode->link = head;
    head=newnode;
   
    return head;
}
struct node* createll(struct node* head, int n)
{
while (n!=0)
{
    head = add_node(head,n%10);
    n=n/10;
}
return head;
}
struct node* reversell(struct node *head)
{
    struct node *p,*q,*r;
    p=head->link;
    q=head;
    r=NULL;
while(p!=NULL)
{
    q->link=r;
    r=q;
    q=p;
    p=p->link;
}
    q->link = r;
    head=q;
    return head;
}

struct node * push (struct node* head , int val)
{
    struct node* newp=malloc(sizeof(struct node));
    newp->data=val;
    newp->link=head;
    head=newp;
    return head;
}
struct node* add(struct node* head1 , struct node* head2)
{
    
    if (head1->data == 0)
    return head2;
    if (head2->data=0)
    return head1;

    struct node* ptr1=head1;
    struct node* ptr2=head2;
    

    struct node* head = NULL;
    int carry=0 , sum=0;
       struct node* head3 = NULL;
    while (ptr1||ptr2)
    {
       sum = 0 ;
       if(ptr1)
       sum += ptr1->data;
       if (ptr2)
       sum += ptr2->data; 
      
       sum += carry;
             
       carry = sum/10;
       sum = sum%10;

       head3 = push (head3 , sum);
       if(ptr1)
       ptr1=ptr1->link;
       if(ptr2)
       ptr2=ptr2->link;
       if (carry && ptr1!=NULL && !ptr2)
       head3 = push (head3 , carry);
    }
       return head3;
}
void print(struct node * head)
{
    
    while(head!=NULL)
    {
        printf("%d ",head->data);
        head=head->link;
    }
}

int main ()
{
    int a,b;
    printf("enter two number");
    scanf("%d %d" , &a,&b );
    
    struct node * head1=NULL;
    head1=createll(head1,a);
    print(head1);
    struct node * head2=NULL;
    head2=createll(head2,b);
    print(head2);
   

    head1 = reversell(head1);
    head2 = reversell(head2);
    
    printf("\nreversed linked list\n");
    print(head1);
    printf("\n");
    print(head2);
    struct node* head3 = NULL;
    head3 = add(head1 , head2);
    printf("\nSum :");
    print(head3);
    return 0 ;
}