linked list operations ( insertion, deletion and display)

Linked list operations ( insertion, deletion and display)



// linked list operations
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<malloc.h>
struct node
{
int info;
struct node *next,*head ;
};
node *head=NULL;
void insertfirst(int);
void insertsp(int);
void insertlast(int);
void deletefirst();
void deletesp();
void deletelast();
void display();
int main()
{

int ch,item;
do
{
printf("\n1) insert at beginning\t2)insert at specified position\t3)insert at last\t4)delete at beginning\t5)delete at specified location\t6)delete last node\t7)display\t8)exit\n");
printf("enter your choice ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("enter the item to be inserted ");
scanf("%d",&item);
insertfirst(item);
break;
case 2:
printf("enter the item to be inserted ");
scanf("%d",&item);
insertsp(item);
break;
case 3:
printf("enter the item to be inserted ");
scanf("%d",&item);
insertlast(item);
break;
case 4:
deletefirst();
break;
case 5:
deletesp();
break;
case 6:
deletelast();
break;
case 7:
display();
break;
case 8:
exit(0);
default:
printf("invalid input");
break;
}
}while(ch<=7);
getch();
}
// INSERTION AT BEGINNING
void insertfirst(int item)
{
node *temp;
temp=(node*)malloc(sizeof(node));
temp->info=item;
if(head==NULL)
temp->next=NULL;
else
temp->next=head;
head=temp;
}
//insertion at specified position
void insertsp(int item)
{
node *temp,*temp1;
int p,i;
temp1=head;
temp=(node*)malloc(sizeof(node));
temp->info=item;
if(head==NULL)
{
temp->next=NULL;
head=temp;
}
else
{
printf("enter the position to insert new node \n");
scanf("%d",&p);
for(i=1;i<=p-1;i++)
temp1=temp1->next;
temp->next=temp1->next;
temp1->next=temp;
}
}
// INSERTION AT THE END
void insertlast(int item)
{
node *nnode,*temp;
temp=head;
nnode=(node*)malloc(sizeof(node));
nnode->info=item;
if(head==NULL)
{
nnode->next=NULL;
head=nnode;
}
else
{
while(temp->next!=NULL)
temp=temp->next;
nnode->next=NULL;
temp->next=nnode;
}
}
// deletion at the first
void deletefirst()
{
node *temp;
if(head==NULL)
{
printf("list empty");
}
else
{
temp=head;
head=head->next;
free(temp);
}
}
// deletion at specified location
void deletesp()
{
node *hold,*temp;
int pos,i;
if(head==NULL)
printf("list empty");
else
{
temp=head;
printf("enter the position to be deleted ");
scanf("%d",&pos);
for(i=1;i<=pos-1;i++)
temp=temp->next;
hold=temp->next;
temp->next=hold->next;
free(hold);
}
}
// deletion at the end
void deletelast()
{
node *hold,*temp;
if(head==NULL)
printf("list empty");
else if (head->next==NULL)
{
hold=head;
head=NULL;
free(hold);
}
else
{
temp=head;
while(temp->next->next!=NULL)
temp=temp->next;
hold=temp->next;
temp->next=NULL;
free(hold);
}
}
// DISPLAYING
void display()
{
node *temp;
temp=head;
printf("\n THE NODES ARE :\n");
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->next;
}
}

OUTPUT



No comments

Powered by Blogger.