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

Tạo Linked List bằng JavaScript

Định nghĩa lớp đơn giản với constructor khởi tạo head = null. Định nghĩa Node trên prototype LinkedList.

Ví dụ

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

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

  • 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 Linked List bằng JavaScript

Triển khai display

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