สมมุติว่าเรามีรายการที่เชื่อมโยงกันแบบนี้ -
const list = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: {
value: 5,
next: {
value: 6,
next: {
value: 7,
next: null
}
}
}
}
}
}
}; เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับหนึ่งในรายการ เช่น อาร์กิวเมนต์แรกและตัวเลขเป็นอาร์กิวเมนต์ที่สอง
ฟังก์ชันควรค้นหาว่ามีโหนดที่มีค่านั้นอยู่ในรายการหรือไม่ หากมี ฟังก์ชันควรลบโหนดออกจากรายการ
ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
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)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
true
{
"value": 1,
"next": {
"value": 2,
"next": {
"value": 4,
"next": {
"value": 6,
"next": {
"value": 7,
"next": null
}
}
}
}
}