Saturday, September 4, 2010

C Program to delete an element from a singly linked list

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
      int data;
      struct node *link;
};
void append(struct node**,int);
void display(struct node*);
void del(struct node **,int);
void main()
{
     struct node *head;

     int n;
     clrscr();
     head=NULL;
     append(&head,5);
     append(&head,6);
     append(&head,7);
     append(&head,8);
     display(head);

     printf(" \n Enter the number you want to delete ");

     scanf("%d",&n);

     del(&head,n);
     display(head);
     getch();
}
void append(struct node **q,int num)
{
     struct node *temp,*r;
     temp=*q;

     if(temp==NULL)  /* If list is empty , create first node */
     {
            temp=(struct node*)malloc(sizeof(struct node));
            temp->data=num;
            temp->link=NULL;
            *q=temp;
     }
     else
     {
          temp=*q;
          while(temp->link !=NULL)
          temp=temp->link;

          r=(struct node*)malloc(sizeof(struct node));
          r->data=num;
          r->link=NULL;
          temp->link=r;
     }
}
void display(struct node *start)
{
     printf("\n");
     printf(" The Linked List is :\n");
     /* Traverse the entire linked list */
     while(start != NULL)
     {
          printf("   %d",start->data);
          start=start->link;
     }

}

void del(struct node **q,int no)
{
     struct node *old,*temp;
     temp=*q;

     while(temp != NULL)
     {
         if(temp->data==no)
        { /* If number to be selected is the first node in the list */
         if(temp==*q)
            *q=temp->link;
         /* Deletes the intermediate nodes from the linked list */
         old->link=temp->link;
         /* Free the memory occupied by the node */
         free(temp);
         return;
      }
        /* Traverse the linked list till the last node is reached */
        else
        {
          old=temp;       /* old points to previous node */

          temp=temp->link;  /* go to the next node */

        }
        }
      printf(" \n Element %d not found ",no);
}

No comments:

Post a Comment