a sample code of writting/reading data into the list
Code:
#include<stdio.h>
#include<string.h>
struct node
{
char name[25];
struct node *link;
};
struct node * getnode()
{
return malloc(sizeof(struct node));
}
void clear_buffer(void)
{
int ch;
while((ch=getchar())!='\n' && ch!=EOF);
}
struct node* insertnode(struct node *h)
{
struct node *p;
int data;
char temp[25];
if(h==NULL)
{
h=getnode();
h->link=NULL;
p=h;
}
else
{
p=getnode();
p->link=h;
}
printf("Enter the name\n?");
clear_buffer();
fgets(temp,sizeof(temp),stdin); // fgets(p->name,sizeof(p->name),stdin) (better way of doing)
strcpy(p->name,temp);
h=p;
return h;
}
displaynodes(struct node *h)
{
while(h!=NULL)
{
printf("%s\n",h->name);
h=h->link;
}
}
int main()
{
struct node *h;
int choice,i,search,del;
h=NULL;
printf("1. Insert an element\n");
printf("2. Display elements\n");
printf("3. Exit \n");
printf("\nEnter your choice\n");
scanf("%d",&choice);
while(choice!=3)
{
switch(choice)
{
case 1:
{
h=insertnode(h);
break;
}
case 2:
{
displaynodes(h);
clear_buffer();
getchar();
break;
}
default:
printf("Error: Invalid input\n");
clear_buffer();
getchar();
}
printf("\n1. Insert an element\n");
printf("2. Display elements\n");
printf("3. Exit \n");
printf("\nEnter your choice\n");
scanf("%d",&choice);
}
}
/*myouput
1. Insert an element
2. Display elements
3. Exit
Enter your choice
1
Enter the name
?john
1. Insert an element
2. Display elements
3. Exit
Enter your choice
1
Enter the name
?alan
1. Insert an element
2. Display elements
3. Exit
Enter your choice
1
Enter the name
?brian
1. Insert an element
2. Display elements
3. Exit
Enter your choice
2
brian
alan
john
*/
ssharish2005