Update appNew update is available. Click here to update.

Delete a Given Node

Last Updated: 2 Dec, 2020
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

Ninja is learning data structures and came across a doubly linked list. Now he wants to remove a particular element from the linked list. Can you help Ninja do so and return the final linked list?

Input Format:
The first line contains a single integer T, denoting the number of test cases. 

The first line of each test case contains a Linked list of length N separated by space and terminated by -1.

The second and last line contains an element that has to be removed from the linked list.
Output Format
The first and only line of each test case in the output contains the linked list after deleting the required element.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function. If there are multiple nodes with the given value remove just the first one.
Constraints:
1 <= T <= 5
1 <= N <= 10^5
-10^5 <= arr[i] <= 10^5

Time Limit: 1 sec

Approach 1

We will traverse the linked list from the head node till we find the node that has to be removed, and upon getting that, we remove it and return the linked list.

 

The steps are as follows:  

  • If the head is NULL, then we don't have to delete anything, return NULL in this case.
  • We declare a node ‘h’ pointing to the head.
  • If the head is equal to the node we have to remove, then we move the head pointer to the node next to the node that needs to be removed.
  • While the Node ‘h’ is not NULL and the value of the Node ‘h’ node is not equal to the given node value traverse linked list.
  • Remove the current node  ‘h’ and return' head' as the final answer.
Try Problem