-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist.js
124 lines (105 loc) · 3.15 KB
/
linkedlist.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
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
//namespace
this.neuronal = this.neuronal || {};
//class
(function() {
"use strict";
//constructor
const LinkedList = function() {
this.head = null;
this.previousNode = null;
this.currentNode = null;
this.length = 0;
};
const proto = LinkedList.prototype;
proto.begin = function() {
if (this.head) {
this.previousNode = null;
this.currentNode = this.head;
return this.head.value;
}
return null;
};
proto.next = function() {
if (this.currentNode && this.currentNode.next) {
this.previousNode = this.currentNode;
this.currentNode = this.currentNode.next;
return this.currentNode.value;
}
return null;
};
proto.end = function() {
if (this.begin() !== null) {
while (this.next()) {}
return this.currentNode.value;
}
return null;
};
proto.push = function(obj) {
const node = {
value: obj,
next: this.head,
previous: null
};
this.head = node;
++this.length;
};
proto.popBack = function() {
if (this.end() !== null) {
const node = this.currentNode;
if (this.previousNode) {
this.previousNode.next = null;
}
--this.length;
if (this.length === 0) {
this.head = this.currentNode = this.previousNode = null;
}
return node.value;
}
return null;
};
proto.removeHere = function() {
const current = this.currentNode;
if (!current) return null;
const next = current.next;
const previous = this.previousNode;
if (next) {
if (previous) { //case: { o -> O -> o }
previous.next = next;
} else { //case: { _ -> O -> o }
this.head = next;
}
this.currentNode = next;
current.next = null;
} else {
if (previous) { //case: { o -> O -> _ }
this.currentNode = previous;
current.next = null;
this.previousNode = null;
} else { //case: { _ -> O -> _ }
this.head = null;
this.currentNode = null;
this.previousNode = null;
}
}
--this.length;
return current.value;
};
proto.find = function(value) {
let currentValue = this.begin();
if (currentValue === null) return false;
if (currentValue === value) return true;
while ((currentValue = this.next()) !== null) {
if (currentValue === value) return true;
}
return false;
};
proto.toArray = function() {
if (this.begin() === null) return null;
const arr = [this.currentNode.value];
while (this.next() !== null) {
arr.push(this.currentNode.value);
}
return arr;
};
neuronal.LinkedList = LinkedList;
})();