Sometime back I asked a question about linked list and got nice replies...Now I've written a new code using the suggestions but I've run into an error. The code is:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
node *mknode()
{
return malloc(sizeof(node));
}
void create(node* h, int num)
{
int i;
node *temp=h;
for(i=0;i<num;i++)
{
temp->data=i;
if(i==(num-1))
temp->next=NULL;
else
temp->next=mknode();
temp=temp->next;
}
}
node* add_end(node *h,int num)
{
node *temp;
if(h==NULL)
{
h=mknode();
temp=h;
create(h,num);
}
else
{
temp=h;
while(h!=NULL){
h=h->next;}
h=mknode();
create(h,num);
}
return temp;
}
void display(node *h)
{
node *temp=h;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
}
int main()
{
node *head=NULL;
int num;
scanf("%d",&num);
head=add_end(head,num);
head=add_end(head,num);
display(head);
//printf("%d",list_len(head));
free(head);
return 0;
}
Now since I've called add_end twice for an input of 3 the output should be 0->1->2->0->1->2-> But instead I'm getting 0->1->2->
I've checked this much that the FOR loop inside create function is running 2n times for an input of n. So the problem is that display function encounters a NULL but I can't figure out where in the code is it happening.
All help appreciated. Thanking in advance -user1614886