Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 链表

作者:佳凝皓月   发布日期:2025-09-30   浏览:104

// 定义链表节点类
class ListNode {
    constructor(value) {
        this.value = value; // 节点的值
        this.next = null;   // 指向下一个节点的指针,默认为null
    }
}

// 定义链表类
class LinkedList {
    constructor() {
        this.head = null; // 链表的头节点,默认为null
    }

    // 向链表尾部添加一个新节点
    append(value) {
        const newNode = new ListNode(value);
        if (!this.head) {
            this.head = newNode;
        } else {
            let current = this.head;
            while (current.next) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    // 打印链表中的所有节点值
    print() {
        let current = this.head;
        let result = [];
        while (current) {
            result.push(current.value);
            current = current.next;
        }
        console.log(result.join(' -> '));
    }
}

// 示例用法
const list = new LinkedList();
list.append(1);
list.append(2);
list.append(3);
list.print(); // 输出: 1 -> 2 -> 3

解释说明

  1. ListNode 类:

    • value: 存储节点的值。
    • next: 指向下一个节点的指针,初始为 null
  2. LinkedList 类:

    • head: 指向链表的第一个节点,初始为 null
    • append(value): 向链表尾部添加一个新节点。如果链表为空,则将新节点设置为头节点;否则遍历到链表末尾并添加新节点。
    • print(): 遍历链表并将所有节点的值打印出来,格式为 1 -> 2 -> 3
  3. 示例用法:

    • 创建一个空的链表 list
    • 使用 append 方法依次添加三个节点,值分别为 1, 2, 3
    • 使用 print 方法打印链表内容,输出结果为 1 -> 2 -> 3

上一篇:js 数组插入数据

下一篇:js arr find

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站