返回信息流面试被问到,不会怎么实现,请问大神们有木有实现过?
这是一条镜像帖。来源:北邮人论坛 / java-script / #378同步于 2016/9/23
该镜像源已超过 30 天没有更新,可能在源站已被删除。
JavaScript机器人发帖
请问大神们,js怎么实现单链表??
bufoshen
2016/9/23镜像同步7 回复
订阅后,新回复会通过你的通知中心匿名送达。
7 条回复
```javascript
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
add(val, pos) {
if (pos < 0 || pos > this.length) throw new Error('blabla');
const node = {
val,
next: null,
};
if (pos === 0) {
node.next = this.head;
this.head = node;
} else {
const prev = this.get(pos - 1);
const cur = prev.next;
node.next = cur;
prev.next = node;
}
this.length += 1;
}
remove(pos) {
if (pos < 0 || pos > this.length) throw new Error('blabla');
if (pos === 0) {
this.head = this.head.next;
} else {
const prev = this.get(pos - 1);
prev.next = prev.next.next;
}
this.length -= 1;
}
get(pos) {
if (pos >= this.length) throw new Error('blabla');
let cur = this.head;
for (let i = 0; i < pos; i++) {
cur = cur.next;
}
return cur;
}
}
```
【 在 steveyoung 的大作中提到: 】
: [md]
: ```javascript
: class LinkedList {
: ...................
振宇大大 es6写的飞起啊