-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlinkedList.js
79 lines (65 loc) · 1.79 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
// Linked List implementation
var LinkedList = function() {
this.head = null;
this.tail = null;
}
var Node = function(value) {
this.value = value;
this.next = null;
};
LinkedList.prototype.appendToTail = function(value) {
// create new Node
var node = new Node(value);
// if linked list is empty then set head and tail to new node
if (this.head === null) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
};
LinkedList.prototype.removeFromHead = function() {
// if the linked list is empty then return null
if (this.head === null) {
return null;
}
// save the head node in order to return it
var node = this.head;
// move the head reference to the next node in the linked list
this.head = this.head.next;
// if the head is now null then the linked list is empty
// update the tail reference to also be null
if (this.head === null) {
this.tail = null;
}
// return the old head node
return node;
};
LinkedList.prototype.removeNode = function(target) {
// if linked list is empty then return false
if (this.head === null) {
return false;
}
// check if head contains target value
if (this.head.value === target) {
this.removeFromHead();
return true;
}
// iterate through the linked list until the target is found or we reach the end of the linked list
var iterator = this.head;
while (iterator.next !== null) {
if (iterator.next.value === target) {
// update the tail reference if we remove the last node
if (iterator.next.next === null) {
this.tail = iterator;
}
iterator.next = iterator.next.next;
return true;
} else {
iterator = iterator.next;
}
}
// target value was not found in the linked list
return false;
};