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

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


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

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

ภาพประกอบ:

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

ตัวอย่าง

insert(data, position = this.length) { 
  let node = new this.Node(data); 
  if (this.head === null) { 
    this.head = node; 
    this.length++; 
    return this.head; 
  } 
  let iter = 1; 
  let currNode = this.head; 
  while (currNode.next != null && iter < position) { 
    currNode = currNode.next; iter++; 
  } 
  node.next = currNode.next; 
  currNode.next = node; 
  this.length++; 
  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