Given a pointer to a node to be deleted, delete the node. Note that we don’t have pointer to head node.
A simple solution 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.
Fast solution is to copy the data from the next node to the node to be deleted and delete the next node. Something like following.
// Find next node using next pointer struct Node *temp = node_ptr->next; // Copy data of next node to this node node_ptr->data = temp->data; // Unlink next node node_ptr->next = temp->next; // Delete next node free(temp);
Before deleting 1 12 1 4 1 After deleting 12 1 4 1
This solution doesn’t work if the node to be deleted is the last node of the list. To make this solution work we can mark the end node as a dummy node. But the programs/functions that are using this function should also be modified.
Exercise: Try this problem for doubly linked list.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
- Delete all Prime Nodes from a Singly Linked List
- Delete all Non-Prime Nodes from a Singly Linked List
- Delete all Prime Nodes from a Circular Singly Linked List
- Select a Random Node from a Singly Linked List
- C Program to reverse each node value in Singly Linked List
- Delete every Kth node from circular linked list
- Delete a node in a Doubly Linked List
- Delete a given node in Linked List under given constraints
- Delete a Linked List node at a given position
- Recursive selection sort for singly linked list | Swapping node links
- Recursive function to delete k-th node from linked list
- Delete a Node from linked list without head pointer
- Delete a Doubly Linked List node at a given position
- Convert singly linked list into circular linked list