Skip to content

Commit 455c6f2

Browse files
committed
feat: add singly linked list
1 parent ea50791 commit 455c6f2

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
class Node {
2+
constructor(value) {
3+
this.value = value
4+
this.next = null
5+
}
6+
}
7+
8+
class LinkedList {
9+
constructor() {
10+
this.head = new Node(null)
11+
this.tail = this.head
12+
}
13+
14+
/**
15+
* @param {number} index
16+
* @return {number}
17+
*/
18+
get(index) {
19+
let i = 0
20+
let current = this.head.next
21+
while (current) {
22+
if (i === index) return current.value
23+
current = current.next
24+
i++
25+
}
26+
return -1
27+
}
28+
29+
/**
30+
* @param {number} value
31+
* @return {void}
32+
*/
33+
insertHead(value) {
34+
const node = new Node(value)
35+
node.next = this.head.next
36+
this.head.next = node
37+
if (!node.next) {
38+
this.tail = node
39+
}
40+
}
41+
42+
/**
43+
* @param {number} value
44+
* @return {void}
45+
*/
46+
insertTail(value) {
47+
const node = new Node(value)
48+
this.tail.next = node
49+
this.tail = this.tail.next
50+
}
51+
52+
/**
53+
* @param {number} index
54+
* @return {boolean}
55+
*/
56+
remove(index) {
57+
let i = 0
58+
let current = this.head
59+
while (current && i < index) {
60+
current = current.next
61+
i++
62+
}
63+
64+
if (current && current?.next) {
65+
if (current.next === this.tail) {
66+
this.tail = current
67+
}
68+
current.next = current.next.next
69+
return true
70+
}
71+
return false
72+
}
73+
74+
/**
75+
* @return {number[]}
76+
*/
77+
getValues() {
78+
const arr = []
79+
let current = this.head.next
80+
while (current) {
81+
arr.push(current.value)
82+
current = current.next
83+
}
84+
return arr
85+
}
86+
}

0 commit comments

Comments
 (0)