-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathLinked List.html
More file actions
144 lines (117 loc) · 3.01 KB
/
Copy pathLinked List.html
File metadata and controls
144 lines (117 loc) · 3.01 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
class Node {
constructor(e, next) {
this.e = e;
this.next = next
}
}
// 链表
class LinkedList {
constructor() {
this.dummyHead = new Node();
this.size = 0;
}
add(index, e) {
if (index < 0 || index > this.size) {
throw new Error("Add failed. Illegal index")
}
let prev = this.dummyHead;
for (let i = 0; i < index; i++) {
prev = prev.next
}
prev.next = new Node(e, prev.next);
this.size++
}
addFirst(e) {
this.add(0, e);
}
addLast(e) {
this.add(this.size, e)
}
get(index) {
if (index < 0 || index > this.size) {
throw new Error("Add failed. Illegal index")
}
let cur = this.dummyHead.next;
for (let i = 0; i < index; i++) {
cur = cur.next
}
return cur.e
}
getFirst() {
return this.get(0)
}
getLast() {
return this.get(this.size - 1)
}
set(index, e) {
if (index < 0 || index > this.size) {
throw new Error("Add failed. Illegal index")
}
let cur = this.dummyHead.next;
for (let i = 0; i < index; i++) {
cur = cur.next
}
cur.e = e
}
contains(e) {
let cur = this.dummyHead.next;
while (cur !== null) {
if (cur.e === e) {
return true
}
cur = cur.next
}
return false
}
remove(index) {
if (index < 0 || index > this.size) {
throw new Error("Add failed. Illegal index")
}
let prev = this.dummyHead;
for (let i = 0; i < index; i++) {
prev = prev.next
}
let delNode = prev.next;
prev.next = delNode.next;
delNode.next = null;
this.size--
}
removeFirst() {
this.remove(0)
}
removeLast() {
this.remove(this.size - 1)
}
removeElement(el) {
let prev = this.dummyHead;
while (prev.next !== null) {
if (prev.next.e === el) {
prev.next = prev.next.next
} else {
prev = prev.next
}
}
this.size--
}
toString() {
let ret = '',
cur = this.dummyHead.next;
while (cur) {
ret += `${cur}->`;
cur = cur.next
}
ret += 'null';
return ret
}
}
</script>
</body>
</html>