I made so many programs on Insertion for Singy Linked separately but this time i gonna combine all those insertion cases into a single program to give you a better understanding about it....
/*All the preprocessors*/
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<stdlib.h>
struct node /*Structure of Singly Linked List*/
{
int data;
struct node *ref;
};
void create(struct node **); /*Create a Singly Linked List*/
void display(struct node *); /*Display a Singly Linked List*/
void addfirst(struct node **); /*Add first in Singly Linked List*/
void addlast(struct node **); /*Add last in Singly Linked List*/
void addmid(struct node **); /*Add middle in Singly Linked List*/
void main()
{
struct node *head=NULL;
int i,af,al,am;
clrscr();
printf("\nEnter no. of element you want to insert :- ");
scanf("%d",&i);
while(i>0)
{
create(&head);
i--;
}
printf("\nDo you want to insert at first (1-->Yes and 0-->No):- ");
scanf("%d",&af);
if(af==1)
{
addfirst(&head);
}
printf("\nDo you want to insert at last (1-->Yes and 0-->No):- ");
scanf("%d",&al);
if(af==1)
{
addlast(&head);
}
printf("\nDo you want to insert at mid (1-->Yes and 0-->No):- ");
scanf("%d",&am);
if(am==1)
{
addmid(&head);
}
display(head);
getch();
}
void create(struct node **q)
{
struct node *temp, *r;
temp=*q;
if(*q==NULL)
{
temp=(struct node *)malloc(sizeof(struct node));
printf("\nEnter value:- ");
scanf("%d",&temp->data);
temp->ref=NULL;
*q=temp;
}
else
{
r=(struct node *)malloc(sizeof(struct node));
printf("\nEnter value :- ");
scanf("%d",&r->data);
r->ref=NULL;
while(temp->ref!=NULL)
{
temp=temp->ref;
}
temp->ref=r;
}
}
void display(struct node *q)
{
while(q!=NULL)
{
printf("\nOUTPUT:- %d",q->data);
q=q->ref;
}
}
void addfirst(struct node **q)
{
struct node *temp, *r;
r=(struct node *)malloc(sizeof(struct node));
printf("\nEnter value:- ");
scanf("%d",&r->data);
temp=*q;
r->ref=temp;
*q=r;
}
void addlast(struct node **q)
{
struct node *temp, *r;
temp=*q;
r=(struct node *)malloc(sizeof(struct node));
printf("\nEnter value:- ");
scanf("%d",&r->data);
r->ref=NULL;
while(temp->ref!=NULL)
{
temp=temp->ref;
}
temp->ref=r;
}
void addmid(struct node **q)
{
int i,pos;
struct node *temp, *r;
temp=*q;
r=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the position for insertion:- ");
scanf("%d",&pos);
printf("\nEnter value:- ");
scanf("%d",&r->data);
r->ref=NULL;
for(i=2;i<pos;i++)
{
temp=temp->ref;
if(temp==NULL)
break;
}
if(temp!=NULL)
{
r->ref=temp->ref;
temp->ref=r;
printf("\n\n\n\nALL THE DATA INSERTED SUCCESSFULLY");
}
}