27、手写链表问题,要求用es6写
时间: 2024-05-14 10:19:41 浏览: 9
好的,关于手写链表问题,下面是一个使用 ES6 类语法实现的链表:
```javascript
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
add(data) {
const newNode = new Node(data);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
remove(data) {
if (!this.head) {
return;
}
if (this.head.data === data) {
this.head = this.head.next;
if (!this.head) {
this.tail = null;
}
return;
}
let cur = this.head;
while (cur.next) {
if (cur.next.data === data) {
cur.next = cur.next.next;
if (!cur.next) {
this.tail = cur;
}
return;
}
cur = cur.next;
}
}
print() {
let cur = this.head;
while (cur) {
console.log(cur.data);
cur = cur.next;
}
}
}
const list = new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.print();
list.remove(2);
list.print();
```
以上代码就是一个简单的使用 ES6 类语法编写的链表。需要注意的是,在 add 和 remove 方法中,需要对头尾节点进行特殊处理。