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

สร้าง Doubly Linked List ใน JavaScript


เริ่มด้วยคลาส constructor เริ่มต้น head และ tail เป็น null กำหนดโครงสร้าง Node ใน prototype ของ DoublyLinkedList

ตัวอย่าง

class LinkedList { 
  constructor() { 
    this.head = null; 
    this.tail = null; 
    this.length = 0; 
  } 
} 
LinkedList.prototype.Node = class { 
  constructor(data) { 
    this.data = data; 
    this.next = null; 
    this.prev = null; 
  } 
};

สร้าง display function ช่วยดูลิสต์: เริ่มจาก head วน currElem = currElem.next จน null พิมพ์ data แต่ละรอบ

ภาพประกอบ:

สร้าง Doubly Linked List ใน JavaScript

ตัวอย่าง

display() { 
  let currNode = this.head; 
  while (currNode != null) { 
    console.log(currNode.data + " -> "); 
    currNode = currNode.next; 
  } 
}