Below is the complete working C code for deleting a node from a linked list.
#include<stdio.h>
#include<stdlib.h>
//linked list structure
struct node
{
int info;
struct node *next;
};
//making typdef so we can use Node instead of 'struct node'
typedef struct node Node;
//inserting node or creating the list or adding the element @ end
Node* insert(Node *h, int info)
{
Node *tempHead=h;
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->info = info;
newNode->next = NULL;
if(tempHead == NULL) // if the list has zero elements. make new node as a head
{
h=newNode;
}
else if(tempHead->next==NULL) // if the list is having only one node
{
tempHead->next = newNode;
}
else
{
Node *tempNode = h;
while(tempNode->next != NULL) // if the list has more than one node, so moving to the last node
{
tempNode = tempNode->next;
}
tempNode->next = newNode; // appending the new node at the end
}
return h;
}
//deleting a node from list. It has three cases
//1. empty list
//2. deleting first node in the list (this is similar to deleting current node in the list)
//3. other than first node
void deleteNode(Node *head, int info)
{
Node *h = head;
Node *temp=NULL;
// empty list
if(h==NULL)
{
printf("Linked list is empty\n");
return ;
}
// deleting node is first node in the list
if(head->info == info)
{
// if list contains only single node
if(head->next == NULL)
{
free(head);
head = NULL;
}
else // list contains multiple nodes
{
head->info = head->next->info;
temp = head->next;
head->next = head->next->next;
free(temp);
h = head->next;
}
printf("----------------- given %d element is deleted from the list----------------- \n",info);
return ;
}
while(h->next!=NULL)
{
if((h->next->info == info))
{
temp = h->next;
h->next=h->next->next;
free(temp);
printf("----------------- given %d element is deleted from the list----------------- \n",info);
return;
}
h=h->next;
}
printf("-------------- %d is not in the list ------------\n",info);
return ;
}
//deleting current node
void deleteCurrent(Node *current)
{
current->info = current->next->info;
current->next = current->next->next;
}
/*****************************************************************************
for displaying the nodes in the list
*****************************************************************************/
void display(Node *h)
{
Node *temp = h;
while (temp->next!=NULL)
{
printf("%d->",temp->info);
temp = temp->next;
}
printf("%d\n",temp->info);
}
int main()
{
Node *head = NULL;
int i,n,element,choice,pos,size;
for (i=1;i<7;i++)
{
head = insert(head,i*2);
}
display(head);
printf("Enter the element to delete from the list\n");
scanf("%d",&element);
deleteNode(head,element);
display(head);
}