File tree 1 file changed +89
-0
lines changed
1 file changed +89
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node {
2
+ constructor ( val ) {
3
+ this . val = val ;
4
+ this . prev = null ;
5
+ this . next = null ;
6
+ }
7
+ }
8
+
9
+ class MyLinkedList {
10
+ constructor ( ) {
11
+ this . head = null ;
12
+ this . tail = null ;
13
+ }
14
+
15
+ get ( index ) {
16
+ let curr = this . head ;
17
+ while ( curr && index > 0 ) {
18
+ curr = curr . next ;
19
+ index -- ;
20
+ }
21
+ return curr ? curr . val : - 1 ;
22
+ }
23
+
24
+ addAtHead ( val ) {
25
+ if ( this . head === null ) {
26
+ this . head = new Node ( val ) ;
27
+ this . tail = this . head ;
28
+ } else {
29
+ this . head . prev = new Node ( val ) ;
30
+ this . head . prev . next = this . head ;
31
+ this . head = this . head . prev ;
32
+ }
33
+ }
34
+
35
+ addAtTail ( val ) {
36
+ if ( this . head === null ) {
37
+ this . head = new Node ( val ) ;
38
+ this . tail = this . head ;
39
+ } else {
40
+ this . tail . next = new Node ( val ) ;
41
+ this . tail . next . prev = this . tail ;
42
+ this . tail = this . tail . next ;
43
+ }
44
+ }
45
+
46
+ addAtIndex ( index , val ) {
47
+ if ( index === 0 ) this . addAtHead ( val ) ;
48
+ else {
49
+ let curr = this . head ;
50
+ while ( curr && index > 0 ) {
51
+ curr = curr . next ;
52
+ index -- ;
53
+ }
54
+ if ( index === 0 ) {
55
+ if ( ! curr ) this . addAtTail ( val ) ;
56
+ else {
57
+ const prev = curr . prev ;
58
+ prev . next = new Node ( val ) ;
59
+ prev . next . prev = prev ;
60
+ prev . next . next = curr ;
61
+ curr . prev = prev . next ;
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ deleteAtIndex ( index ) {
68
+ if ( ! this . head ) return ;
69
+ if ( index === 0 ) {
70
+ this . head = this . head . next ;
71
+ if ( this . head ) this . head . prev = null ;
72
+ } else {
73
+ let curr = this . head ;
74
+ while ( curr && index > 0 ) {
75
+ curr = curr . next ;
76
+ index -- ;
77
+ }
78
+ if ( curr && index === 0 ) {
79
+ if ( ! curr . next ) {
80
+ curr . prev . next = null ;
81
+ this . tail = curr . prev ;
82
+ } else {
83
+ curr . prev . next = curr . next ;
84
+ curr . next . prev = curr . prev ;
85
+ }
86
+ }
87
+ }
88
+ }
89
+ }
You can’t perform that action at this time.
0 commit comments