VOOZH about

URL: https://www.geeksforgeeks.org/dsa/delete-occurrences-given-key-linked-list/

⇱ Delete all occurrences of a given key in a linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Delete all occurrences of a given key in a linked list

Last Updated : 4 Sep, 2024

Given a singly linked list, the task is to delete all occurrences of a given key in it.

Examples:

Input: head: 2 -> 2 -> 1 -> 8 -> 2 -> NULL, key = 2
Output: 1 -> 8 -> NULL

👁 Delete-all-occurrences-of-a-given-key-in-a-linked-list

Explanation: All occurrences of the given key = 2, is deleted from the Linked List


Input: head: 1 -> 1 -> 1 -> 4 -> 1 -> NULL, key = 1
Output: 4 -> NULL

👁 Delete-all-occurrences-of-a-given-key-in-a-linked-list_1

Explanation: All occurrences of the given key = 1, is deleted from the Linked List.

Approach:

The Idea is to traverse the list while maintaining a prev pointer to track the previous node. If the current node contains the key, update the next pointer of the prev node to the current node, effectively removing it from the list. This process continues until the end of the list, ensuring all nodes with the specified key are removed.

Below is the implementation of the above idea:


Output
 1 8

Time complexity: O(n), where n is the number of nodes in the list.
Auxiliary Space: O(1)

Comment
Article Tags: