Delete A Node in Linked List

Delete A Node in Linked List:-Data Structure and algorithms

To delete a node from linked list, we need to do following steps.
1) Find previous node of the node to be deleted.

2) Changed next of previous node.

3) Free memory for the node to be deleted.

Since every node of linked list is dynamically allocated using malloc() in C,
we need to call free() for freeing memory allocated for the node to be deleted


#include<stdio.h>
#include<stdlib.h>

struct node{int data;
struct node *next;
};


void insert(struct node **head,int new_data)
{

struct node *new_node;
new_node=(struct node*)malloc(sizeof(struct node));

new_node->data=new_data;
new_node->next=*head;
*head=new_node;

}

void DeleteNode(struct node **head,int key)
{

struct node *temp,*prev;

temp=*head;

if(temp!=NULL&&temp->data==key)
{

/*   temp=temp->next;
     *head=temp;
*/

//or

*head=temp->next;
free(temp);

}

while(temp!=NULL&&temp->data!=key)
{

prev=temp;
temp=temp->next;

}

//delete node
if(temp==NULL)
{
printf("Element not found in List\n");
return;
}

prev->next=temp->next;

}

void traverse(struct node *head)
{
while(head!=NULL)
{
printf("%d\t",head->data);
head=head->next;
}
printf("\n");
}
main()

{

struct node *head;

insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);

traverse(head);

DeleteNode(&head,3);

traverse(head);
}

Related Posts