Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การลบโหนดออกจาก Singly Linked List ใน JavaScript

มี Singly Linked List ที่แทนด้วยออบเจกต์ซ้อน {value, next} ต้องเขียนฟังก์ชันลบโหนดที่มีค่าตรงกับพารามิเตอร์ที่ส่งเข้าไป

ตัวอย่างโค้ด

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));

ผลลัพธ์

ค่าที่แสดงในคอนโซลจะเป็นดังนี้:

true
{
  "value": 1,
  "next": {
    "value": 2,
    "next": {
      "value": 4,
      "next": {
        "value": 6,
        "next": {
          "value": 7,
          "next": null
        }
      }
    }
  }
}