源代码

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

// 定义链表类
class LinkedList {
    constructor() {
        this.head = 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;
        }
    }

// 遍历链表并输出每个节点的值
    traverse() {
        let current = this.head;
        while (current) {
            console.log(current.value);
            current = current.next;
        }
    }
}

// 创建一个包含 100 个节点的链表,每个节点存储一个随机整数
const linkedList = new LinkedList();
for (let i = 0; i < 100; i++) {
    const randomValue = Math.floor(Math.random() * 100); // 生成 0 到 99 的随机整数
    linkedList.append(randomValue);
}

// 遍历链表并输出每个节点的整数
linkedList.traverse();

运行结果示例

45 72 13 89 24 56 91 8 67 33 ... (省略剩余的随机数输出)