Deletion Operation on Singly Linked List

To delete a node from linked list can be performed in 3 positions:

  1. Delete from beginning
  2. Delete given node
  3. Delete from end

Delete from beginning:

  • Store address of first node(head) in temporary node pointer.
  • Move head to second node in linked list.
  • Free memory of temporary node.
void del_begin(){
  struct node *temp;
  if(head==NULL){
    printf("List is empty.\n");
  }else{
    temp=head;
    head=head->next;
    free(temp);
  }
}

Delete given node:

void del_givennode(){
  int nodeval;
  struct node *ptr1,*ptr2;
  if(head==NULL){
    printf("List is empty.");
  }else{
    printf("Enter node value:\n");
    scanf("%d",&nodeval);
    ptr2=head;
    while(ptr2->next!=NULL && ptr2->data!=nodeval){
      ptr1=ptr2;
      ptr2=ptr2->next;
    }
    if(ptr2->data==nodeval){
      ptr1->next=ptr2->next;
      free(ptr2);
    }else{
      printf("Node value not found in list.\n");
    }
  }
}

Delete from end:

  • Move to two pointers, one(ptr2) points to last node of linked list another(ptr1) points to last but one node.
  • Change address field of ptr1 with NULL to show it as last node.
  • Free memory of ptr2
void del_end(){
  struct node *ptr1,*ptr2;
  if(head==NULL){
    printf("List is empty.\n");
  }else{
    ptr2=head;
    while(ptr2->next!=NULL){
      ptr1=ptr2;
      ptr2=ptr2->next;
    }
    free(ptr2);
    ptr1->next=NULL;
  }
}

Click on the below button for implementation of Singly Linked List with it's operations.

Singly Linked List



Related Programs


  1. Create Singly Linked List with N number of nodes and display.
  2. Perform insertion operation on Singly Linked List.
  3. Perform deletion operation on Singly Linked List.
  4. Reverse of Singly Linked List.
  5. Move last node of Singly Linked List to first.
  6. Swap first and last nodes in a Singly Linked List.
  7. Find the length of Singly Linked List.
  8. Find middle node of Singly Linked List

No comments:

Post a Comment

Total Pageviews