-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.js
40 lines (35 loc) · 925 Bytes
/
linked_list.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
//Linked list
function LinkedList() {
this.head = null;
this.tail = null;
}
function Node(value, prevNode, nextNode) {
this.value = value;
this.prevNode = prevNode;
this.nextNode = nextNode;
}
LinkedList.prototype.addToHead = function(value) {
var newNode = new Node(value, null, this.tail);
if(this.head !== null) {
if(this.tail !== null) newNode.nextNode = this.tail;
this.head.nextNode = newNode;
}else {
this.head = newNode;
if(this.tail === null) {
this.tail = newNode;
}
}
}
LinkedList.prototype.addToTail = function(value) {
var newNode = new Node(value, this.tail, null);
if(this.tail !== null) {
this.tail.prevNode = newNode;
}else {
this.tail = newNode;
}
if(this.head === null) this.head = newNode;
}
var llst = new LinkedList();
llst.addToHead(50);
llst.addToTail(40);
console.log(llst);