-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkList.js
More file actions
76 lines (67 loc) · 1.57 KB
/
linkList.js
File metadata and controls
76 lines (67 loc) · 1.57 KB
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
class Node {
constructor(element) {
this.element = element;
this.next = null;
}
}
class LinkList {
constructor() {
this.head = new Node('head');
}
// 查找一个节点
find(item) {
let currentNode = this.head;
while (currentNode.element !== item) {
currentNode = currentNode.next;
}
return currentNode;
}
// 查找输入节点前一个节点
findPre(item) {
if (item === 'head') {
throw new Error('你要删除节点是头节点');
}
let currentNode = this.head;
while (currentNode.next && currentNode.next.element !== item) {
currentNode = currentNode.next;
}
return currentNode;
}
// 插入一个新节点
insert(newElement, item) {
const newNode = new Node(newElement);
const currentNode = this.find(item);
newNode.next = currentNode.next;
currentNode.next = newNode;
}
// 删除一个新节点
remove(item) {
let preNode = this.findPre(item);
if (preNode.next.element === item) {
preNode.next = preNode.next.next;
}
}
// 展示出所有的链表
toString() {
let currentNode = this.head;
let str = '';
while (currentNode.next !== null) {
currentNode = currentNode.next;
str += currentNode.element;
console.log(currentNode);
if (currentNode.next !== null) str += ' <- ';
}
return str;
}
};
// e.g
// const LL = new LinkList();
//
// LL.insert('a1', 'head');
// LL.insert('a2', 'a1');
// LL.insert('a3', 'a2');
// LL.insert('a4', 'a3');
// LL.remove('a2');
//
// console.log(LL);
// console.log(LL.toString());