Deletion in linked list in C++ : Linked List – 3
February 11, 2011 Leave a comment
Question. We are given a singly linked list and a pointer to a node to be deleted. We wish to delete that node.
We could proceed as follows:
// the function deletes node pointed to by x from the linked list.
// returns true if deletion was successful; else, returns false.
bool deleteNode ( Node **head, Node *x)
if ( ! head )
// empty list
Node *curr = *head;
if ( x == *head) //special case: delete first node
head = head -> next ;
while (curr != 0 && curr -> next != x)
curr = curr -> next;
if ( ! curr)
//node not found.
//deleting the node
curr -> next = x -> next;
Note that we need to pass a pointer to the head pointer since the location the head pointer points to may change (in case of deletion of first node).