Giả sử, chúng ta có một danh sách liên kết đơn như sau:
const list = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: {
value: 5,
next: {
value: 6,
next: {
value: 7,
next: null
}
}
}
}
}
}
};Chúng ta cần viết một hàm JavaScript nhận vào một danh sách như vậy làm đối số thứ nhất và một số làm đối số thứ hai. Hàm nên tìm kiếm xem có tồn tại nút với giá trị đó trong danh sách không, nếu có, hàm nên xóa nút đó khỏi danh sách.
Ví dụ
Code cho việc này sẽ là:
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) => {
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));Kết quả
Kết quả hiển thị trong console sẽ là:
true
{
"value": 1,
"next": {
"value": 2,
"next": {
"value": 4,
"next": {
"value": 6,
"next": {
"value": 7,
"next": null
}
}
}
}
}