-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkNode.js
80 lines (65 loc) · 1.26 KB
/
LinkNode.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Node {
constructor(element) {
this.element = element;
this.next = null;
}
}
/**
* 链表
*/
class LinkNodeList {
constructor() {
this.head = null;
this.length = 0;
}
append(element) {
let node = new Node(element);
let cur = null;
if (this.head === null) {
this.head = node;
} else {
cur = this.head;
while (cur.next) {
cur = cur.next;
}
cur.next = node;
}
this.length += 1;
}
removeAt(index) {
let cur = this.head;
let i = 0;
let prev;
if (index === 0) {
this.head = cur.next;
} else {
// 找到待删除节点,循环完毕,则表示已经找到待删除节点
while (i < index) {
prev = cur;
cur = cur.next;
i++;
}
prev.next = cur.next;
cur.next = null;
}
this.length -= 1;
}
toString() {
let cur = this.head;
let res = [];
while (cur) {
res.push(cur.element);
cur = cur.next;
}
return res.join("==>");
}
}
const list = new LinkNodeList();
list.append("Hello");
list.append("world");
list.append("你今天好吗");
list.append("我今天很好");
console.log(list.toString());
list.removeAt(2);
list.toString();
console.log(list.toString());