Traverse the linked list recursively and remove every alternate node. At each step, adjust the current nodeβs next pointer to bypass the next node, effectively deleting it. Then move to the next valid node using recursion and repeat the process until the end of the list is reached.
Algorithm:
If the node is NULL or node->next is NULL, stop recursion.
Store the next node to be deleted in a temporary pointer: temp = node->next
Update the link to skip the node: node->next = temp->next
Delete the skipped node: delete(temp)
Move to the next valid node using recursion: deleteAlt(node->next)
Note : temp and delete(temp) are needed in C and C++ only as automatic garbage collection does not happen there.
Output
List before calling deleteAlt()
1 2 3 4 5
List after calling deleteAlt()
1 3 5
Iterative Approach - O(n) Time O(1) Space
Maintain a pointer to the node just before the one to be deleted, Update its next link to skip the unwanted node. Then move forward and repeat the process for the remaining list.
Algorithm:
Start from the head of the linked list.
If the list is empty (head == NULL), stop.
Set prev = head and node = head->next.
Traverse the list while both prev and node are not NULL.
Update the link to skip the node to be deleted: prev->next = node->next
Delete the node: delete(node)
Move prev to the next valid node: prev = prev->next
If prev is not NULL, update: node = prev->next
Note : delete(mode) ste needed in C and C++ only as automatic garbage collection does not happen there.
Output
List before deletion:
1 2 3 4 5
List after deleting:
1 3 5
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem.