Friday, 8 December 2017

Deletion of a node in a Linked List:

Another primitive operation that can be done in a singly linked list is the deletion of a node. Memory is to be released for the node to be deleted. A node can be deleted from the list from three different places namely.
a. Deleting a node at the beginning.
b. Deleting a node at the end.
c. Deleting a node at intermediate position.

Deleting a node at the beginning of Linked List:
The following steps are followed, to delete a node at the beginning of the list:
a. If list is empty then display 'Empty List' message.
b. If the list is not empty, follow the steps given below: 
temp = start;
start = start ->next;
free(temp);
The function delete_at_beg(), is used for deleting the first node in the list.
void delete_at_beg()
{
node *temp; if(start ==NULL)
{
printf("\n No nodes are exist..");
return ;
}
else
{
temp = start;
start = temp -> next;
free(temp);
printf("\n Node deleted ");
}
}

Deleting a node at the end of Linked List:
The following steps are followed to delete a node at the end of the list:
a. If list is empty then display 'Empty List' message.
b. If the list is not empty, follow the steps given below:
temp = prev = start;
while(temp -> next != NULL)
{
prev = temp;
temp = temp -> next;
}
prev -> next = NULL;
free(temp);
The function delete_at_last(), is used for deleting the last node in the list.
void delete_at_last()
{
node *temp, prev;
if(start == NULL)
{
printf("\n Empty List.."); return ;
}
else
{
temp = start;
prev = start;
while(temp -> next != NULL)
{
prev = temp;
temp = temp -> next;
}
prev -> next = NULL;
free(temp);
printf("\n Node deleted ");
}
}

Deleting a node at Intermediate position of Linked List:
The following steps are followed, to delete a node from an intermediate position in the list (List must contain more than two node).
a. If list is empty then display 'Empty List' message
b. If the list is not empty, follow the steps given below.
if(pos > 1 && pos < nodectr)
{
temp = prev = start; ctr = 1;
while(ctr < pos)
{
prev = temp;
temp = temp -> next;
ctr++;
}
prev -> next = temp -> next;
free(temp);
printf("\n node deleted..");
}


Thanks
Mukesh Rajput

No comments:

Post a Comment

Thanks
Mukesh Rajput