I've just started learning C and am fairly a beginner. Today in school we learned linked list and I was able to put up a code...which thankfully is running without errors.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*head;//*temp;
void create(struct node **h,int num)
{
int i;
struct node *temp=*h;
for(i=0;;i++)
{
if(i>=num)
break;
temp->data=i;
temp->next=malloc(sizeof(struct node));
temp=temp->next;
}
temp->next=NULL;
}
void display(struct node **h)
{
struct node *temp=*h;
while(temp->next!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
printf("\b\b \b\b");
}
void append_end(struct node **h,int val)
{
struct node *temp=*h,*temp1;
//printf("'%d'",val);
while(temp->next!=NULL)
temp=temp->next;
temp1=malloc(sizeof(struct node));
temp1->data=val;
temp1->next=NULL;
temp->next=temp1;
}
void free_list(struct node **h)
{
struct node *temp=*h,*tail;
while(temp->next!=NULL)
{
tail=temp;
temp=temp->next;
free(tail);
}
h=NULL;
}
int main()
{
head=malloc(sizeof(struct node));
int i,num;
scanf("%d",&num);
create(&head,num);
//display(&head);
append_end(&head,5);
append_end(&head,6);
display(&head);
/*temp=head;
while(temp->next!=NULL)
temp=temp->next;
printf("%d",temp->data);*/
free_list(&head);
return 0;
}
The expected output should be 0->1->2->3->5->6 for input of 4
But instead I'm getting 0->1->2->3->(some garbage value)->5
I'll be glad if someone could point out my error(s), and/or link to any article that might help me in understanding the topic clearly.
Thanks in advance.