#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *link;
}NODE;
NODE * get_node()
{
NODE *p;
p = (NODE*)malloc(sizeof(NODE));
printf("Enter data:");
scanf("%d",&p->data);
p->link = NULL;
return p;
}
NODE * create_sll()
{
int n,i;
NODE *first,*last,*q;
printf("Enter no.of nodes:");
scanf("%d",&n);
first = last = NULL;
for(i=1;i<=n;i++)
{
q = get_node();
if(first==NULL)
first = q;
else
last->link = q;
last = q;
}
return first;
}
void display(NODE *h)
{
while(h!=NULL)
{
printf("%4d",h->data);
h=h->link;
}
printf("\n");
}
NODE* insert_first(NODE *h)
{
NODE *q;
q = get_node();
if(h!=NULL)
q->link=h;
h = q;
return h;
}
void main()
{
NODE *h=NULL;
int ch,pos;
while(1)
{
printf("1.Create\n");
printf("2.Display\n");
printf("3.Insert at first position\n");
printf("4.Exit\n");
printf("Enter your choice (1-4):");
scanf("%d",&ch);
switch(ch)
{
case 1:
h = create_sll();
break;
case 2:
display(h);
break;
case 3:
h=insert_first(h);
break;
case 4:
exit(0);
}
getch();
}
}
Output-
1.Create
2.Display
3.Insert at first position
4.Exit
Enter your choice (1-4): 1
Enter no.of nodes:1
Enter data:2
1.Create
2.Display
3.Insert at first position
4.Exit
Enter your choice (1-4):2
2
1.Create
2.Display
3.Insert at first position
4.Exit
Enter your choice (1-4):3
Enter data:1
1.Create
2.Display
3.Insert at first position
4.Exit
Enter your choice (1-4):2
1 2
1.Create
2.Display
3.Insert at first position
4.Exit
Enter your choice (1-4):4