-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
66 lines (56 loc) · 1.25 KB
/
index.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
module.exports = LinkedList
LinkedList.Node = Node
function Node(data) {
this.prev = null
this.next = null
this.data = data
}
function LinkedList() {
this.length = 0
this.first = null
this.last = null
}
LinkedList.prototype.append = function(node) {
if (this.first === null) {
this.first = node.prev = node
this.last = node.next = node
} else {
node.prev = this.last
node.next = this.first
this.first.prev = node
this.last.next = node
this.last = node
}
this.length += 1
}
LinkedList.prototype.insert = function(node, inserted) {
inserted.prev = node
inserted.next = node.next
node.next.prev = inserted
node.next = inserted
if (inserted.prev === this.last) this.last = inserted
this.length += 1
}
LinkedList.prototype.remove = function(node) {
if (this.length > 1) {
node.prev.next = node.next
node.next.prev = node.prev
if (node === this.first) this.first = node.next
if (node === this.last) this.last = node.prev
} else
if (this.first === node) {
this.first = null
this.last = null
}
node.prev = null
node.next = null
this.length -= 1
}
LinkedList.prototype.each = function(cb) {
var p = this.first
var n = this.length
while (n--) {
cb(p.data)
p = p.next
}
}