Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tạo Doubly Linked List bằng JavaScript

Định nghĩa lớp đơn giản với constructor khởi tạo head, tail = null. Định nghĩa cấu trúc Node trên prototype DoublyLinkedList.

Ví dụ

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

Tạo hàm display() để xem cấu trúc list:

  • Bắt đầu từ head
  • Duyệt currElem = currElem.next cho đến null
  • In data mỗi lần lặp

Minh họa:

Tạo Doubly Linked List bằng JavaScript

Triển khai display

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