File tree Expand file tree Collapse file tree 1 file changed +86
-0
lines changed
interview/neetcode/implement Expand file tree Collapse file tree 1 file changed +86
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments