Friday, 8 September 2017

Deletion operation in Linked List

In the previous tutorial, we had learned all the basic concept of a linked list, like what is linked list, the structure of a linked list, Insertion operation.
Now it's time to learn about the deletion operation in a Linked list. Likewise insertion operation, deletion operation may also be performed in three ways:-

  1. Deletion of the first node
  2. Deletion of the middle node
  3. Deletion of the last node
Deletion of the first node:-

void delete_First()
{
  struct node *temp;
   if(start==NULL)
   { 
     printf("List is empty");
     return;
   }
   else
   {
     r=start;
     start=start->next;
     free(r);
    }
   return;
 }

Deletion of the last node:-

void delete_Last()
{
  struct node *p,*q;

if(start==NULL)
{
  printf("List is Empty");
          return;
}
else
{
 p=start;
while(p->next!=NULL)
 {
q=p;
p=p->next;
 }
 q->next=NULL;
 free(p);
       }
   return;
 }

Deletion of the middle node:-

void delete_mid()
{
  struct node *r, *temp, *prev, *p;
  if(start==NULL)
    {
      printf("List is empty");
      return;
     }
  if(start->next==NULL)
   {
     r=start;
     start=NULL;
     free(r);
     return;
    }
   temp=start;
   p=start;
   while(temp!=NULL && temp->next!=NULL)
    {
      temp=temp->next->next;
      prev=p;
      p=p->next;
     }
   prev->next=p->next;
   free(p);
   return;
 }

No comments:

Post a Comment