-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked-list.js
112 lines (97 loc) · 1.9 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
append(value) {
const node = new Node(value);
if (this.head === null) {
this.head = node;
} else {
this.tail.nextNode = node;
}
this.tail = node;
}
prepend(value) {
const node = new Node(value);
if (this.head === null) {
this.tail = node;
} else {
node.nextNode = this.head;
}
this.head = node;
}
size() {
let temp = this.head;
let size = 0;
while (temp !== null) {
size++;
temp = temp.nextNode;
}
return size;
}
head() {
return this.head;
}
tail() {
return this.tail;
}
at(index) {
let temp = this.head;
for (let i = 0; i < index; i++) {
temp = temp.nextNode;
}
return temp;
}
pop() {
let temp = this.head;
while (temp !== null && temp.nextNode !== this.tail) {
temp = temp.nextNode;
}
return temp;
}
contains(value) {
let temp = this.head;
while (temp !== null && temp.value !== value) {
temp = temp.nextNode;
}
return temp !== null;
}
find(value) {
let temp = this.head;
let index = 0;
while (temp !== null && temp.value !== value) {
temp = temp.nextNode;
index++;
}
if (temp === null) {
index = null;
}
return index;
}
toString() {
let string = "";
let temp = this.head;
while (temp !== null) {
string += `( ${temp.value} ) -> `;
temp = temp.nextNode;
}
string += "null";
return string;
}
}
class Node {
constructor(value) {
this.value = value;
this.nextNode = null;
}
}
// Test
const list = new LinkedList();
console.log("Empty list size: " + list.size());
list.append(1);
list.append(2);
list.append(3);
console.log("Size of 3: " + list.size());
console.log("Second element should be 2: " + list.at(1).value);
console.log(list.toString());