forked from fay-jai/toy-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedList.js
78 lines (65 loc) · 1.48 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
/*
* Implement a linked list using the pseudoclassical instantiation pattern.
*
* Your linked list should have methods called "addToTail", "removeHead", and "contains."
*
*/
// EXAMPLE USAGE:
// var list = new LinkedList();
// list.addToTail(4);
// list.contains(4); //yields 'true';
// list.removeHead();
// list.tail; //yields 'null';
var LinkedList = function () {
this.head = null;
this.tail = null;
};
//write methods here!
LinkedList.prototype.addToTail = function (value) {
var newNode = this.makeNode(value);
if (this.isEmpty()) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
};
LinkedList.prototype.removeHead = function () {
var result;
if (!this.isEmpty()) {
result = this.head.value;
if (this.head === this.tail) {
this.head = null;
this.tail = null;
} else {
this.head = this.head.next;
}
return result;
}
};
LinkedList.prototype.contains = function (value, node) {
if (this.isEmpty()) {
return false;
}
// initialize node
if (node === void 0) {
node = this.head;
}
if (node === null) {
return false;
} else if (node.value === value) {
return true;
} else {
return this.contains(value, node.next);
}
};
LinkedList.prototype.isEmpty = function () {
return this.head === null && this.tail === null;
};
LinkedList.prototype.makeNode = function (value) {
return {
value : value,
next : null
};
};