다음과 같은 단일 연결 목록이 있다고 가정해 보겠습니다. -
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
}
}
}
}
}