Delete a node, given the pointer

♠ Posted by GeekyFry in ,,,,,, at 7:02 AM
Given only a pointer to a node to be deleted in a singly linked list, how do you delete it ?

Possible Solution:
Most simple solution that would come to mind is to traverse the linked list until you find the node you want to delete. But this solution requires pointer to the head node which contradicts the problem statement.
Solution is to copy the data from the next node to the node to be deleted and delete the next node:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* Link list node */
struct node
{
 int data;
 struct node* next;
};
 
void deleteNode(struct node *node_ptr)
{
 struct node *temp = node_ptr->next;
 node_ptr->data = temp->data;
 node_ptr->next = temp->next;
 free(temp);
}

0 comments:

Post a Comment