Delete a node in a singly linked list(Faster Mehtod)

Delete a node in a singly linked list(Fater Mehtod):-(Not Work For Last Node)

Other Approch which is Fast Compare to Iterative Method
1. Copy the data from the next node to the node to be deleted
    and delete the next node

#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 *key)  //key a node which is deleted
{
if(key->next!=NULL)
{
struct node *temp;
temp=key->next;
key->data=temp->data;
key->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->next->next->next);

traverse(head);
}

Related Posts