-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlinkedlist.js
59 lines (47 loc) · 1.18 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
(function(){
var LinkedList = function(){
this.head = null;
this.tail = null;
var Node = function(val){
this.value = val;
this.next = null;
};
this.addToTail = function(val){
if (!this.tail){
this.head = new Node(val);
this.tail = this.head;
} else {
var oldTail = this.tail;
this.tail = new Node(val);
oldTail.next = this.tail;
}
};
this.removeFromHead = function(){
var oldHead = this.head;
this.head = oldHead.next;
if (this.head === null){this.tail=null;}
return oldHead;
};
this.size = function(){
var size = this.head ? 1 : 0;
for (var node = this.head; node.next ; node = node.next){
size++;
};
return size;
};
this.each = function(cb){
for (var node = this.head; node ; node = node.next){
cb(node.value);
}
};
};
var root = this;
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = LinkedList;
}
exports.LinkedList = LinkedList;
} else {
root.LinkedList = LinkedList;
}
})();