用js 写一个链表遍历
时间: 2023-07-18 14:33:29 浏览: 43
好的,下面是一个用 JavaScript 实现的链表遍历的示例代码:
```javascript
// 链表节点类
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// 链表类
class LinkedList {
constructor() {
this.head = null;
}
// 添加节点
addNode(data) {
const node = new Node(data);
// 如果链表为空,则将新节点设置为头节点
if (!this.head) {
this.head = node;
} else {
// 否则找到链表末尾,将新节点添加到末尾
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
}
// 遍历链表并打印节点数据
traverse() {
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
}
// 示例使用
const list = new LinkedList();
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.traverse(); // 输出:1 2 3
```
以上代码中,我们定义了 `Node` 类表示链表节点,`LinkedList` 类表示链表。`LinkedList` 类包含 `addNode` 方法用于添加节点,和 `traverse` 方法用于遍历链表并打印节点数据。我们创建一个示例链表,并依次添加节点 `1`、`2`、`3`,然后调用 `traverse` 方法遍历并打印节点数据。