Simple Program to delete given node from linked list

C Program for deletion of a given node from linked list. For example if linked list is 2->3->23->7->54->34 then we are given to delete a node in which data is 23 or 34.

C Program:

#include<stdio.h>
#include<stdlib.h>
 
struct Node 
{
 int data;
 struct Node *next;
};
 
struct Node *CreateNode(int n)
{
struct Node *newNode=(struct Node*)malloc(sizeof(struct Node));
    newNode->data = n;
    newNode->next = NULL;
    return newNode;
}
 
struct Node *Insert(struct Node *head,int n)
{
 struct Node *newNode = CreateNode(n);
 if(head==NULL)
 {
  head = newNode;
 }
 else
 {
  newNode->next = head;
  head = newNode;
 }
 
 return head;
 
}
struct Node *Delete(struct Node *head,int n)
{
 struct Node *temp;
 if(head==NULL)
 return head;
 else
 {
  temp = head;
 /* Find all nodes in which data is n and 
 delete then from linked list. In this while 
 we are checking all nodes except head node*/
  while(temp->next!=NULL)
  {
  if(temp->next->data==n)
  {
  struct Node *temp1 = temp->next;
  temp->next = temp1->next;
  free(temp1);
  }
  else
  {
  temp = temp->next;
  }
  }
 }
 /* Here we are checking head node whether 
 data in head node is equal to n or not */
 if(head->data==n)
 {
  struct Node *temp1 = head;
  head = temp1->next;
  free(temp1);
 }
 return head;
}
 
void PrintList(struct Node *head)
{
 struct Node *curr = head;
 if(curr==NULL)
 {
  printf("List is empty");
 }
 else
 {
  while(curr!=NULL)
 {
     printf("%d ",curr->data);
  curr = curr->next;  
 }
 }
 printf("\n");
}
 
int main()
{
 struct Node *head = NULL;
 head = Insert(head,54);
 head = Insert(head,65);
 head = Insert(head,98);
 head = Insert(head,36);
 PrintList(head);
 head = Delete(head,54);
 head = Delete(head,98);
 head = Insert(head,76);
 PrintList(head);
 
 return 0;
 
}
 
 



Popular posts from this blog