/*********************************************************************/
/*PROGRAM TO INSERT A NEW NODE IN THE BEGINNING OF LINEAR LINKED LIST*/
/*********************************************************************/
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<process.h>
#include<ctype.h>
struct linear_list
{
int info;
struct linear_list *next;
}*start,*newnode,*ptr;
void menu();
void create();
void display_traverse();
int list_empty();
int count();
void insert_beg(int);
void main()
{
clrscr();
menu();
}
void menu()
{
int choice,loc,loc1,item,num,var;
printf("MENU");
printf("\n1. Create");
printf("\n2. Display/Traverse");
printf("\n3. Insertion in the beginning");
printf("\n4.Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
create();
clrscr();
printf("The created linked list is:\n");
display_traverse();
getch();
clrscr();
menu();
break;
case 2:
clrscr();
if(list_empty()==1)
{
printf("The linked list is:\n");
display_traverse();
}
getch();
clrscr();
menu();
break;
case 3:
clrscr();
printf("\nEnter the item tobe inserted: ");
scanf("%d",&item);
insert_beg(item);
clrscr();
printf("\nAfter insertion in the beginning the linked list is:\n");
display_traverse();
getch();
clrscr();
menu();
break;
case 4:
exit(1);
default:
clrscr();
printf("Your choice is wrong\n\n");
menu();
}
}
void create()
{
int item;
char ch;
clrscr();
newnode=(struct linear_list*)malloc(sizeof(struct linear_list));
start=newnode;
do
{
printf("\nEnter data: ");
scanf("%d",&item);
newnode->info=item;
printf("\nDo you want to create another node:(y/n)");
fflush(stdin);
scanf("%c",&ch);
if(tolower(ch)=='y')
{
newnode->next=(struct linear_list*)malloc(sizeof(struct linear_list));
newnode=newnode->next;
}
else
{
newnode->next=NULL;
}
}while(tolower(ch)!='n');
}
void display_traverse()
{
int i;
ptr=start;
i=1;
while(ptr!=NULL)
{
printf("\nNode %d : %d",i,ptr->info);
ptr=ptr->next;
i++;
}
}
int list_empty()
{
if(start==NULL)
{
printf("\nLinked List is empty");
return(0);
}
else
{
return(1);
}
}
void insert_beg(int item)
{
newnode=(struct linear_list*)malloc(sizeof(struct linear_list));
newnode->info=item;
if(start==NULL)
{
start=newnode;
newnode->next=NULL;
}
else
{
newnode->next=start;
start=newnode;
}
}