-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.js
More file actions
120 lines (112 loc) · 2.55 KB
/
LinkedList.js
File metadata and controls
120 lines (112 loc) · 2.55 KB
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
112
113
114
115
116
117
118
119
120
/**
* Class Node
*/
class Node {
/**
* Define Node constructor.
* @param {Number} value
* @param {Node} next
*/
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}
/**
* Class LinkedList
*/
class LinkedList {
/**
* Define LinkedList constructor.
*/
constructor() {
this.head = null;
}
/**
* get index value.
* @param {Number} index
* @returns
*/
get(index) {
let current = this.head;
let count = 0;
while (current !== null) {
if (count === index) {
return current.value;
}
count++;
current = current.next;
}
return -1; // index out of bounds
}
/**
* insert a new head.
* @param {number} value
*/
insertHead(value) {
const newNode = new Node(value, this.head);
this.head = newNode;
}
/**
* insert a tail node.
* @param {number} value
*/
insertTail(value) {
const newNode = new Node(value);
if (this.head === null) {
this.head = newNode;
} else {
let current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = newNode;
}
}
/**
* remove node by index number.
* @param {number} index
* @returns
*/
remove(index) {
if (this.head === null) {
return false; //list is empty
}
if (index === 0) {
this.head = this.head.next;
return true;
}
let current = this.head;
let count = 0;
while (current !== null) {
if (count === index - 1 && current.next !== null) {
current.next = current.next.next;
return true;
}
count++;
current = current.next;
}
return false; // index out of bounds
}
/**
* get all node values
* @returns {Array} values
*/
getValues() {
const values = [];
let current = this.head;
while (current !== null) {
values.push(current.value);
current = current.next;
}
return values;
}
}
// Example Usage:
const list = new LinkedList();
list.insertHead(1);
list.insertTail(2);
list.insertHead(0);
console.log(list.remove(1)); // Output: true
console.log(list.getValues()); // Output: [0, 2]
console.log(list.get(5)); // Output: -1