Suppose, we have a singly linked list like this −
const list = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: {
value: 5,
next: {
value: 6,
next: {
value: 7,
next: null
}
}
}
}
}
}
};We are required to write a JavaScript function that takes in one such list as the first argument and a number as the second argument.
The function should search whether there exists a node with that value in the list, if it does, the function should remove the node from the list.
Example
The code for this will be −
const list = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: {
value: 5,
next: {
value: 6,
next: {
value: 7,
next: null
}
}
}
}
}
}
};
const recursiveTransform = (list = {}) => {
if(list && list['next']){
list['value'] = list['next']['value'];
list['next'] = list['next']['next'];
return recursiveTransform(list['next']);
}else{
return true;
};
}
const removeNode = (list = {}, val, curr = list) => {
// end reached and item not found
if(!list){
return false;
}
if(list['value'] !== val){
return removeNode(list['next'], val, list);
};
return recursiveTransform(list);
};
console.log(removeNode(list, 3));
console.log(JSON.stringify(list, undefined, 4));Output
And the output in the console will be −
true
{
"value": 1,
"next": {
"value": 2,
"next": {
"value": 4,
"next": {
"value": 6,
"next": {
"value": 7,
"next": null
}
}
}
}
}