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

Singly Linked List dạng Circular (vòng) trong JavaScript

Circular Singly Linked List: Danh sách liên kết đơn vòng tròn. Con trỏ next của node cuối trỏ về node đầu (head). Chỉ duyệt 1 chiều, vòng lặp vô tận.

Cấu trúc Node

class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

Đặc điểm

  • tail.next = head
  • Không có prev pointer.
  • Chỉ duyệt forward, không thể đi lùi.
  • Cần giữ reference đến tail để insert/delete cuối O(1).

Thao tác cơ bản

Insert at end (O(1) nếu có tail)

insertLast(data) {
  const node = new Node(data);
  if (!this.head) {
    this.head = node;
    node.next = node; // self-loop
    this.tail = node;
  } else {
    node.next = this.head;
    this.tail.next = node;
    this.tail = node;
  }
}

Delete (phức tạp hơn doubly)

Cần duyệt từ head tìm node trước node cần xóa (prev) để cập nhật prev.next. O(n).

Ứng dụng

  • Round-robin scheduler đơn giản.
  • Circular buffer / Ring buffer (fixed size queue).
  • Game entity loop đơn giản.

Singly Linked List dạng Circular (vòng) trong JavaScript