Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //program to calculate sum of two long integers using linked list
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct node *nodeptr;
- struct node{
- int data;
- nodeptr next;
- };
- list_print(nodeptr s)
- {
- if(s->next!=NULL)
- {
- list_print(s->next);
- printf("%d",s->data);
- }
- else{printf("%d",s->data);}
- }
- list_print_str(nodeptr s)
- {
- while(s->next!=NULL)
- {
- printf("%d",s->data);
- s=s->next;
- }
- printf("%d",s->data);
- }
- int num_list_add_leng(nodeptr s ,char str[])
- {
- int len=strlen(str);
- int x=0;
- while(x<len)
- {
- int d=(int)str[x]-(int)'0';
- nodeptr temp=NULL;
- temp=malloc(sizeof(nodeptr));
- temp->next=s->next;
- s->next=temp;
- temp->data=d;
- x++;
- }
- return (len);
- }
- initialize(nodeptr one,nodeptr two,nodeptr ans)
- {
- one->next=NULL;
- two->next=NULL;
- ans->next=NULL;
- one->data=0;
- two->data=0;
- }
- int bfr=0;
- add(nodeptr one,nodeptr two,nodeptr ans)
- {
- int ad1,ad2;
- while(1){
- if((one->next!=NULL)&&(two->next!=NULL))
- {
- one=one->next;
- ad1=one->data;
- two=two->next;
- ad2=two->data;
- }
- else{
- if((one->next==NULL)&&(two->next!=NULL))
- {
- ad1=0;
- two=two->next;
- ad2=two->data;
- }
- else{
- {
- ad2=0;
- one=one->next;
- ad1=one->data;
- }
- }
- }
- nodeptr temp=NULL;
- temp=malloc(sizeof(nodeptr));
- temp->next=ans->next;
- ans->next=temp;
- temp->data=(ad1+ad2+bfr)%10;
- bfr=(ad1+ad2+bfr)>9?1:0;
- if((one->next==NULL)&&(two->next==NULL))
- break;
- }
- if(bfr)
- {
- nodeptr temp=NULL;
- temp=malloc(sizeof(nodeptr));
- temp->next=ans->next;
- ans->next=temp;
- temp->data=1;
- }
- }
- main()
- {
- nodeptr one=NULL;
- nodeptr two=NULL;
- nodeptr ans=NULL;
- one=malloc(sizeof(nodeptr));
- two=malloc(sizeof(nodeptr));
- ans=malloc(sizeof(nodeptr));
- initialize(one,two,ans);
- char a[10000];
- printf("first number ");
- scanf("%s",a);
- int l1=num_list_add_leng(one,a);
- printf("\n second number ");
- scanf("%s",a);
- int l2=num_list_add_leng(two,a);
- list_print(one->next);
- printf("\n");
- list_print(two->next);
- printf("\n");
- add(one,two,ans);
- list_print_str(ans->next);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement