Saturday, 18 March 2017

C Program to delete a node from Singly Linked List

C Progam to delete a node from Singly Linked List is given below. In this program we used 2 functions beside main() function. The one function is delete() function which will perform the deleting operation in the Linked List at the specified position and the second function is print() function which will print the Linked List before deletion and insertion.

Algorithm:

delete(int node_number)
If  node_number = 1:
           set:   head=head.next
Else:
           set: current =head
           do While  current!=NULL:
                        set: count=count+1
                        if(count=node_number-1):
                                      current.next=current.next.next
                                      break loop
                        set: current=current.next
           End While
End IfElse

Program:


#include <stdio.h>
#include <stdlib.h>
void delete(int node_number);
void print();
struct node
{
   int data;
   struct node *next;
}*head=NULL,*temp;
int main()
{
   int node_number;

      /*generating a linked list for example */

   temp=(struct node*)malloc(sizeof(struct node));
      temp->data=12;
      temp->next=NULL;
      head=temp;
      temp->next=(struct node*)malloc(sizeof(struct node));
      temp=temp->next;
      temp->data=56;
      temp->next=(struct node*)malloc(sizeof(struct node));
      temp=temp->next;
      temp->data=33;
      temp->next=(struct node*)malloc(sizeof(struct node));
      temp=temp->next;
      temp->data=44;
      temp->next=(struct node*)malloc(sizeof(struct node));
      temp=temp->next;
      temp->data=526;
      temp->next=(struct node*)malloc(sizeof(struct node));
      temp=temp->next;
      temp->data=6;
      temp->next=NULL;

      printf("\nLinked list before deletion:\n");
      print();
      printf("\n\nEnter the node you want to delete: ");
      scanf("%d",&node_number);

      /*calling delete function to delete the node*/

      delete(node_number);

      printf("\n\nLinked list after deletion:\n");
      print();
      printf("\n");
      return 0;
}
void delete(int node_number)
{
   struct node *current;
   int count=0;
   if(node_number==1)
   {
            head=head->next;
   }
   else
   {
        current=head;
        while(current!=NULL)
        {
             count++;
             if(count==node_number-1)
             {
                current->next=current->next->next;
                break;
             }
             current=current->next;
        }
   }
}
void print()
{
   struct node *current;
   current=head;
   while(current!=NULL)
   {
         printf("%d->",current->data);
         current=current->next;
   }
}


OUTPUT:

 


EmoticonEmoticon