Back to photostream

Remove Linked List Elements Leetcode Solution

Problem Statement

In this problem, we are given a linked list with its nodes having integer values. We need to delete some nodes from the list which have value equal to val. The problem does not require to be solved in-place but we will discuss one such approach.

Example

List = 1 -> 2 -> 2 -> 3 -> 4 , val = 2

1 3 4

List = 2 -> 2 -> 2 -> 2 , val = 2

Empty List

 

Approach (Recursive)

We can recursively call the same function to return the head of the required list. We achieve this by calling the function on subsequent suffixes of the given list with some conditions. However, we need to handle the base case when the list is empty. There is only one special case:

 

If the head of the list has a value equal to val(input), then, we need to return the function called on its next node. This is done to avoid the current node to be appended to the previous nodes of the list (as the function stack is completed).

Implementation of Remove Linked List Elements Leetcode Solution

C++ Program

#include

 

using namespace std;

 

struct listNode

{

int value;

listNode* next;

listNode(int x)

{

value = x;

next = NULL;

}

};

 

void print(listNode* head)

{

if(head == NULL) {

cout next;

head->next = NULL;

delete(head);

return removeElements(temp , val);

}

 

head->next = removeElements(head->next , val);

return head;

}

 

int main() {

listNode* head = new listNode(1);

head->next = new

 

www.tutorialcup.com/leetcode-solutions/remove-linked-list...

31 views
0 faves
0 comments
Uploaded on August 12, 2021