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

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


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

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

ภาพประกอบ:

Remove 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; 
  } else if (position >= this.length - 1) { 
    while (currNode.next.next != null) { 
      currNode = currNode.next; 
    } 
    currNode.next = null; 
  } else { 
    let iter = 0; 
    while (iter < position) { 
      currNode = currNode.next; iter++; 
    } 
    currNode.next = currNode.next.next; 
  } 
}

ทดสอบ:

ตัวอย่าง

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