// 定义链表节点类
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
ListNode 类:
value
: 存储节点的值。next
: 指向下一个节点的指针,初始为 null
。LinkedList 类:
head
: 指向链表的第一个节点,初始为 null
。append(value)
: 向链表尾部添加一个新节点。如果链表为空,则将新节点设置为头节点;否则遍历到链表末尾并添加新节点。print()
: 遍历链表并将所有节点的值打印出来,格式为 1 -> 2 -> 3
。示例用法:
list
。append
方法依次添加三个节点,值分别为 1
, 2
, 3
。print
方法打印链表内容,输出结果为 1 -> 2 -> 3
。上一篇:js 数组插入数据
下一篇:js arr find
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站