Here is a linked list code in C , It does not give expected output .
Input
NUMBER OF ELEMENTS -3
but it takes only 2 element and prints them with an extra zero.
here is the output
**ENTER THE NUMBER OF ELEMENTS
3
1
2
The list contains 0
The list contains 1
The list contains 2
**
#include<stdio.h>
struct list{
int data;
struct list* next;
};
struct list* insert(struct list* node,int data)
{
struct list* newnode=malloc(sizeof(struct list));
if(newnode)
{
newnode->data=data;
newnode->next=NULL;
}
if(node)
{
while(node->next)
{
node=node->next;
}
node->next=newnode;
}
return newnode;
}
void printlist(struct list *node)
{
if(!node)
{
printf("empty list\n");
}
while(node)
{
printf("The list contains %d \n",node->data);
node=node->next;
}
}
int main()
{
struct list *temp;
temp=malloc(sizeof(struct list));
int i,n,m;
printf("ENTER THE NUMBER OF ELEMENTS\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&m);
insert(temp,m);
}
printlist(temp);
}