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

Remove Doubly Linked List ใน JavaScript: ลบโหนด 3 กรณี


การลบสมาชิกใน linked list ง่าย แค่ทำให้สูญเสีย reference มี 3 กรณี:

  • ลบจาก head: head = head.next และลบ previous link ของโหนดถัดไป สูญเสีย reference ตัวแรก head ชี้ตัวที่สอง
  • ลบจาก tail: node.next ของตัวก่อนสุดท้ายเป็น null และอัปเดต tail ชี้โหนดปัจจุบัน
  • ลบจากกลาง: prevNode.next = node.next และ node.next.prev = prevNode

ภาพประกอบ:

Remove Doubly Linked List ใน JavaScript: ลบโหนด 3 กรณี

ตัวอย่าง

remove(data, position = 0) { 
  if (this.length === 0) { 
    console.log("List is already empty"); 
    return; 
  } 
  this.length--; 
  let currNode = this.head; 
  if (position <= 0) { 
    this.head = this.head.next; 
    this.head.prev = null; 
  } else if (position >= this.length - 1) { 
    this.tail = this.tail.prev; 
    this.tail.next = null; 
  } else { 
    let iter = 0; 
    while (iter < position) { 
      currNode = currNode.next; 
      iter++; 
    } 
    currNode.next = currNode.next.next; 
    currNode.next.prev = currNode; 
  } 
  return currNode; 
}

ตัวอย่าง

ทดสอบ:

let list = new LinkedList(); 
list.insert(10); 
list.insert(20); 
list.insert(30); 
list.remove(1); 
list.display(); 
list.insert(15, 2); 
list.remove(); 
list.display();

ผลลัพธ์

จะได้ผลลัพธ์:

20 <-> 30 <-> 30 <-> 15 <->