47 views

Is my analysis correct?

I analyze code that if it will take

1->2->3 and 4->1->2 as input

then output will be reverse of 5->3->2 i.e. 2->3->5

Why code is showing runtime error?

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
struct node
{
char digit;
struct node * next;
};
struct node * makenode(char digit)
{
struct node *A;
//int count=0;
A=NULL;
struct node *temp=(struct node*)malloc(sizeof(struct node));
//while(((temp->next)==NULL) && (count<3)){
//temp=(struct node*)malloc(sizeof(struct node));
temp->next=digit;
temp->next=NULL;
A=temp;
//count++;
}
return 0;
}

void printList(struct node * list)
{
printf("%d->",*list);
}
{
char c;
struct node * head, * trav;
scanf("%c", &c);
do
{
scanf("%c", &c);
if(!isdigit(c)) break;
trav -> next = makenode(c - '0');//more nodes are created and as input is in char, 48
//subtracted from each node
trav = trav -> next;

}while(1);
}
struct node* reverse(struct node * list, struct node **head)
{
if(list -> next == NULL)
{
return list;
}
reverse(list -> next, head) -> next = list;
list -> next = NULL;
return list;
}
struct node * simultrav(struct node* trav1, struct node * trav2, char carry)
{
struct node * temp;
char sum = carry;
if(trav1 && trav2)
{
sum += trav1 -> digit + trav2 -> digit;
}
else if (trav1)
{
sum += trav1 -> digit;
}
else if (trav2)
{
sum += trav2 -> digit;
}
carry = sum /10;
sum = sum % 10;
temp = makenode(sum);

if(trav1  && trav2)
{
temp -> next = simultrav(trav1-> next, trav2 -> next, carry);
}
else if(trav1)
{
temp -> next =  simultrav(trav1-> next, trav2, carry);
}
else if(trav2)
{
temp -> next =  simultrav(trav1, trav2 -> next, carry);
}
else
{
if(carry)
{
temp -> next = makenode(carry);
}
else
temp -> next = NULL;
}
return temp;
}

int main()
{
struct node * num1, * num2, *rnum1, *rnum2, *sum, *rsum;
printf("Enter the first number: ");
printf("Enter the second number: ");
printf("\n");
reverse( num1, &rnum1);
reverse( num2, &rnum2);
rsum = simultrav(rnum1, rnum2, 0);
reverse( rsum, &sum);
printf("The sum is : ");
printList(sum);
printf("\n");
return 0;
}

+1
You should return temp in makenode function.

Also, in printList, you should traverse till NULL and print all node values. This was a pretty simple assignment more to familiarize all with linkedlists.
0
Summation of reverse list, is new type question to me, I always getting runtime error.

thank u
0
and why u r subtracting 0?

I understood, as u paased the character in it

but still not clear to me
+1
That is to convert char to int. I'm reading digits as char but storing in list as an int of 8 bits size. i.e. say for 2, read value using %c will be its ASCII code 50, but I store the value 50 - 48 = 2 only.
+1
yes , I understood now :)
+1

in makenode()

temp->next=digit;

should be temp->digit= digit

in simultrav(),

even though, both lists are completed and carry=0, it will create one more node with value = 0 and make it's next as NULL