You are on page 1of 7

//Single Linked list implementation

#include<stdio.h>
#include<string.h>
#define null 0
void create();
void ins_beg();
void ins_end();
void ins_pos();
void display();
struct node
{
int rollno;
char name[20];
struct node *link;
};
struct node *start=null,*p,*q;
void main()
{
int ch;
clrscr();
while(1)
{
printf("\n1.Create a linked list");
printf("\n2.Insert a node in front of list");
printf("\n3.Insert a node at the end of the list");
printf("\n4.Insert a node at a given position");
printf("\n5.Display linked list");
printf("\n6.Exit\n");
printf("\nEnter your choice:");
scanf("%d",&ch);
clrscr();
switch(ch)
{
case 1:
create();
break;
case 2:
printf("\nLinked list before inserting the node\n");
display();
ins_beg();
printf("\nLinked list after inserting the node\n");
display();
break;
case 3:
printf("\nLinked list before inserting the node\n");
display();
ins_end();
printf("\nLinked list after inserting the node\n");
display();
break;
case 4:
printf("\nLinked list before inserting the node\n");
display();
ins_pos();
printf("\nLinked list after inserting the node\n");
display();
break;
case 5:
display();
break;
case 6:
exit(0);
default:printf("\nInvalid choice");
}
}
}
void create()
{
char choice='y';
clrscr();
start=null;
q=null;
while(choice=='y')
{
p=((struct node*)malloc(sizeof(struct node)));
printf("\nEnter the rollno & name :");
scanf("%d %s",&p->rollno,p->name);
p->link=null;
if(start==null)
{
start=p;
q=p;
}
else
{
q->link=p;
q=p;
}
printf("\nDo you want to create another node y/n :");
choice=getche();
}
}
void ins_beg()
{
p=((struct node*)malloc(sizeof(struct node)));
printf("\nEnter register number:");
scanf("%d",&p->rollno);
printf("\nEnter name of student:");
scanf("%s",&p->name);
p->link=start;
start=p;
}
void ins_end()
{
p=(struct node *)malloc(sizeof(struct node));
printf("\nEnter register number:");
scanf("%d",&p->rollno);
printf("\nEnter name of student:");
scanf("%s",&p->name);
p->link=null;
if(start==null)
{
start=p;
}
else
{
q=start;
while(q->link!=null)
{
q=q->link;
}
q->link=p;
}
}
void ins_pos()
{
int i,pos;
printf("\nEnter the position at which you want to insert the new
node:");
scanf("%d",&pos);
if(pos==1)
ins_beg();
else
{
q=start;
for(i=1;i<pos-1;i++)
{
q=q->link;
}
p=(struct node *)malloc(sizeof(struct node));
printf("\nEnter register number:");
scanf("%d",&p->rollno);
printf("\nEnter name of student:");
scanf("%s",&p->name);
p->link=q->link;
q->link=p;
}
}
void display()
{
printf("\n\n The nodes in the list are\n\nSTART->");
p=start;
while(p!=null)
{
printf("%d %s ->",p->rollno,p->name);
p=p->link;
}
printf("NULL\n");
return;
}

You might also like