forked from AllAlgorithms/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedList.js
More file actions
111 lines (96 loc) · 2.21 KB
/
linkedList.js
File metadata and controls
111 lines (96 loc) · 2.21 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
// LinkedList and Node function Constructor
function LinkedList() {
this.head = null;
this.tail = null;
};
function Node(value, next, prev) {
this.value = value;
this.next = next;
this.prev = prev;
};
// Add to head
LinkedList.prototype.addHead = function(value) {
var newNode = new Node(value, this.head, null);
if(this.head) {
this.head.prev = newNode;
} else {
this.tail = newNode;
}
this.head = newNode;
};
var LL = new LinkedList();
LL.addHead(100);
LL.addHead(200);
LL.addHead(300);
LL.addHead(200);
console.log(LL);
// Add to tail
LinkedList.prototype.addTail = function(value) {
var newNode = new Node(value, null, this.tail);
if(this.tail) {
this.tail.next = newNode;
}else {
this.head = newNode;
}
this.tail = newNode;
};
LL.addTail(100);
LL.addTail(200);
LL.addTail(300);
console.log(LL);
console.log(ll.head.value);
// Remove from head
LinkedList.prototype.removeHead = function(){
if(this.head == null) {
return null;
}
else {
var val = this.head.value;
this.head = this.head.next;
}
if(!this.head) this.tail = null;
return val;
};
var ll = new LinkedList();
console.log(LL.removeHead());
console.log(LL);
// Remove from tail
LinkedList.prototype.removeTail = function() {
if(!this.tail) return null;
var val = this.tail.value;
this.tail = this.tail.prev;
if(this.tail) this.tail.next = null;
else this.head = null;
return val;
}
console.log(LL.removeTail());
console.log(LL.removeTail());
console.log(LL.removeTail());
console.log(LL);
// search in LinkedList
LinkedList.prototype.search = function(searchValue) {
if(!this.head) return null;
var currentNode = this.head;
while(currentNode){
if(currentNode.value === searchValue) return currentNode.value;
currentNode = currentNode.next;
}
return null;
}
console.log(LL.search(100));
// find indexOf element in LinkedList
LinkedList.prototype.indexOf = function(value) {
if(!this.head) return null;
var currentNode = this.head;
var counter = 0;
var indexArr = new Array;
while(currentNode){
if(currentNode.value === value){
indexArr.push(counter);
}
counter++;
currentNode = currentNode.next;
}
return indexArr;
}
console.log(LL.indexOf(200));