Previous | Home | Next |
Just as in case of the singly or linear linked lists, deletions can be performed in the three ways too :
- Deletion from the front of the linked list.
- Deletion from the end of the linked list.
- Deletion from the specified position in the linked list.
Now we will see how we can perform all types of deletion operations on a linked list through the following code snippet :
#include<conio.h>
#include<malloc.h>
#include<process.h>
struct node
{
int num;
struct node *next;
}; /* declaring a global node of type struct */
typedef struct node NODE; /* providing a type definition to the above created structure */
NODE *head=NULL; /* declaring some of the global variable that would be used throughout the program */
NODE *temp, *first, *last;
int info;
void display();
void create_list();
void del_at_begin();
void del_at_end();
void del_at_specifiedpos();
void main() /* starting the main method() */
{
int i;
clrscr();
printf("\nprogram for deletion in a singly linked list :\n");
do
{
printf("\nEnter your choice :\n"); /* creating menu for various insertion operations on the list */
printf("\n1.Create a linked list :");
printf("\n2.Delete from the front in the linked list :");
printf("\n3.Delete from the end position in the linked list :");
printf("\n4.Delete at any specified position in the linked list :");
printf("\n5.Exit\n");
fflush(stdin);
scanf("\n%d",&i);
switch(i)
{
case 1:
create_list();
display();
case 2:
del_at_begin();
display();
break;
case 3:
del_at_end();
display();
break;
case 4:
del_at_specifiedpos();
display();
break;
case 5:
exit(0);
}
}
while(i!=5);
getch();
}
void create_list()
{
printf("\nEnter your element in the linked list :");
scanf("%d",&info);
temp=(NODE *)malloc(sizeof(NODE)); /* allocating memory for the node to be inserted */
temp->num=info;
temp->next=NULL;
if(head==NULL) /* checking whether list is empty */
{
temp->next=temp;
head=temp;
last=temp;
}
else
{
last->next=temp;
last=temp;
last->next=head;
}
}
void display()
{
if(head==NULL)
printf("linked list is empty");
else
{
first=head;
printf("\nStatus of the linked list is as follows :\n");
while(first->next!=head) /* traversing the linked list */
{
printf("\n%d",first->num);
first=first->next;
}
}
}
void del_at_begin()
{
if(head==NULL)
{
printf("linked list is empty");
}
else
{
temp=head;
head=head->next;
last->next=head;
free(temp);
}
}
void del_at_end()
{
if(head==NULL)
{
printf("\nlinked list is empty");
}
else
{
temp=head;
while(temp->next!=last)
{
first=temp;
temp=temp->next;
}
first->next=temp->next;
last=first;
free(temp);
}
}
void del_at_specifiedpos()
{
int node_num;
if(head==NULL)
{
printf("\nlinked list is empty");
}
else
{
temp=head;
printf("\nEnter the position of the node you want to delete");
scanf("\n%d",&node_num);
for(int i=1;i<node_num;i++)
{
first=temp;
temp=temp->next;
}
first->next=temp->next;
free(temp);
}
}
Previous | Home | Next |