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

Insert Doubly Linked List ใน JavaScript: เพิ่มโหนดที่ตำแหน่งกำหนด


สร้างฟังก์ชัน insert(data, position) ใส่ข้อมูลที่ตำแหน่งกำหนดใน doubly linked list ขั้นตอน:

  • สร้าง Node ใหม่
  • ตรวจสอบว่ารายการว่าง ถ้าใช่เพิ่มที่ head และ tail แล้ว return
  • ถ้าไม่ วนลูปไปตำแหน่งที่ต้องการด้วย currElem (currElem = currElem.next)

เปลี่ยนลิงก์ดังนี้:

  • โหนดใหม่ชี้ไปโหนดถัดไป
  • โหนดถัดไป previous ชี้กลับโหนดใหม่
  • โหนดใหม่ previous ชี้โหนดก่อนหน้า
  • โหนดก่อนหน้า next ชี้โหนดใหม่

สุดท้าย put link จาก currElem ไปโหนดใหม่ โหนดอยู่ในลิสต์ที่ตำแหน่งที่กำหนดแล้ว

ภาพประกอบ:

Insert Doubly Linked List ใน JavaScript: เพิ่มโหนดที่ตำแหน่งกำหนด

ตัวอย่าง

insert(data, position = this.length) { 
  let node = new this.Node(data); 
  this.length++; 
  if (this.head === null) { 
    this.head = node; 
    this.tail = node; 
    return this.head; 
  } 
  if (position == 0) { 
    node.prev = null; 
    node.next = this.head; 
    this.head.prev = node; 
    this.head = node; 
    return this.head; 
  } 
  let iter = 1; 
  let currNode = this.head; 
  while (currNode.next != null && iter < position) { 
    currNode = currNode.next; 
    iter++; 
  } 
  node.next = currNode.next; 
  if (currNode.next != null) { 
    currNode.next.prev = node; 
  } 
  node.prev = currNode; 
  currNode.next = node; 
  if (this.tail.next != null) { 
    this.tail = this.tail.next; 
  } 
  return node; 
}

position default เป็นท้ายสุด หากไม่ระบุจะใส่ท้ายอัตโนมัติ

ทดสอบ:

ตัวอย่าง

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

ผลลัพธ์

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

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

สมาชิกเรียงตามที่ตั้งใจ 15 ถูกแทรกหลังตำแหน่ง 2