top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

D.S : Write a C program which gives the result of subtraction of two numbers represented by linked list ?

+2 votes
543 views

Result should be stored in new linked list.

posted Sep 4, 2016 by Ganesh

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
#include<stdio.h>
#include<malloc.h>
struct list
{
    int data;
    struct list*next;   
};

struct list *head3=NULL,*head4=NULL, *head1=NULL,*head2=NULL,*head5=NULL;
struct list* push(struct list* head,int data)
{
    struct list *new=(struct node*)malloc(sizeof(struct list));
    new->data=data;
    new->next=NULL;
    if(head==NULL)
    {
        head=new;   
    }
    else
    {
        new->next=head;
        head=new;
    }
    return head;
}
void print(struct list*head)
{
    if(head==NULL)
    printf("empty");
    else
    {
        while(head)
        {
            printf("%d",head->data);
            head=head->next;
        }
    }
}
struct list* rev(struct list*head)
{
    struct list *temp=NULL,*prev=NULL;
    if(head==NULL)
    return 0;
    else
    {

        while(head)
        {
            temp=head->next;
            head->next=prev;
            prev=head;
            head=temp;
        }
    }
    return prev;

}
struct list *sub(struct list*up,struct list*lo)
{
    if(head1==NULL||head2==NULL)
    return 0;
    else
    {
        printf("\n");
        head1=rev(head1);
        printf("\n");
        print(head1);
        head2=rev(head2);
        printf("\n");
        print(head2);
        printf("\n");
        while(head2!=NULL)
        {
            if(head1->data>=head2->data)
            {   
                head3=push(head3,(head1->data)-(head2->data));
            }
            else
            {

                head1->next->data=head1->next->data-1;
                head1->data+=10;    
                head3=push(head3,(head1->data)-(head2->data));
            }
            head1=head1->next;
            head2=head2->next;
        }

            head3=push(head3,head1->data);

        printf("\n");
        print(head3);

    }   
}
int main()
{
    head1=push(head1,1);
    head1=push(head1,3);
    head1=push(head1,5);
    head1=push(head1,4);
    print(head1);
    head2=push(head2,1);
    head2=push(head2,4);
    head2=push(head2,9);
    printf("\n");
    print(head2);
    sub(head1,head2);
}
answer Sep 18, 2016 by Shishir Chaudhary
Writing few lines about the code/algorithm helps to understand the code better.
Similar Questions
+3 votes
+2 votes

I am looking for sample code which can impress an interviewer.

–1 vote

Given a Singly linked list with each node containing either 0, 1 or 2. Write code to sort the list.
Input : 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> 0
Output : 0 -> 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2

...