-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinked_list.js
93 lines (76 loc) · 1.77 KB
/
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
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
function Node(data) {
this.data = data;
this.next = null;
}
function LinkedList() {
this._length = 0;
this.head = null;
}
LinkedList.prototype.add = function(value) {
var node = new Node(value), currentNode = this.head;
// 1st use-case: an empty list
if (!currentNode) {
this.head = node;
this._length++;
return node;
}
// 2nd use-case: a non-empty list
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
this._length++;
return node;
};
LinkedList.prototype.delete = function(value) {
var currentNode = this.head;
// 1st use-case: an empty list
if (!currentNode) {
return;
}
// 2nd case: if first element in the list
if (currentNode.data === value) {
if (currentNode.next) {
this.head = currentNode.next
return;
} else {
this.head = null;
return;
}
}
// 3rd use-case: a non-empty list
while (currentNode && currentNode.next) {
if(currentNode.next.data === value) {
if (!currentNode.next.next) { // for last element in list
currentNode.next = null;
} else {
currentNode.next = currentNode.next.next;
}
}
currentNode = currentNode.next;
}
this._length--;
return;
};
var list = new LinkedList();
list.add("These");
list.add("words");
list.add("are");
list.add("elements");
list.add("in");
list.add("a");
list.add("linked list");
list.add(".");
// var pointer = list.head;
// while(pointer !== null){
// console.log(pointer.data);
// pointer = pointer.next;
// }
list.delete(".");
list.delete("These");
list.delete("linked list");
var pointer = list.head;
while(pointer !== null){
console.log(pointer.data);
pointer = pointer.next;
}