-
Notifications
You must be signed in to change notification settings - Fork 0
/
ES6_ClassLinkedList.js
93 lines (81 loc) · 1.43 KB
/
ES6_ClassLinkedList.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
const expect = require('expect');
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
display() {
return this;
}
addToTail(val) {
const newNode = this.node(val);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
}
else if (this.tail) {
this.tail.next = newNode;
}
else {
this.tail = newNode;
}
}
addToHead(val) {
const newNode = this.node(val);
const temp = this.head;
this.head = newNode;
this.head.next = temp;
}
removeHead() {
if(!this.head) {
return null;
}
let temp = this.head;
this.head = this.head.next;
return temp;
}
contains(target) {
let node = this.head;
while (node) {
if (this.head.value === target) {
return true;
}
node = node.next;
}
return false;
}
reverse() {
let node = this.head;
let prev = null;
while (node) {
let temp = node.next;
node.next = prev;
prev = node;
node = temp;
}
return prev;
}
traverse(cb) {
let node = this.head;
while (node) {
cb(node.value);
node = node.next;
}
}
node(val) {
return {
value: val,
next: null
};
}
}
const testFunction = () => {
const x = new LinkedList();
x.addToHead(4);
x.addToHead(6);
expect(
x.contains(6)
).toEqual(true);
};
testFunction();
console.log('All tests passed');