File tree 1 file changed +13
-11
lines changed
src/_DataStructures_/LinkedList
1 file changed +13
-11
lines changed Original file line number Diff line number Diff line change @@ -2,21 +2,22 @@ class Node {
2
2
constructor ( data , next ) {
3
3
this . data = data ;
4
4
this . next = next ;
5
- this . length = 0 ;
6
5
}
7
6
}
8
7
9
8
class LinkedList {
10
9
constructor ( ) {
11
10
this . head = null ;
12
11
this . tail = null ;
12
+ this . size = 0 ;
13
13
}
14
14
15
15
addAtBeginning ( element ) {
16
16
this . head = new Node ( element , this . head ) ;
17
17
if ( ! this . tail ) {
18
18
this . tail = this . head ;
19
19
}
20
+ this . size += 1 ;
20
21
return this . head ;
21
22
}
22
23
@@ -27,19 +28,20 @@ class LinkedList {
27
28
const node = new Node ( element , null ) ;
28
29
this . tail . next = node ;
29
30
this . tail = node ;
31
+ this . size += 1 ;
30
32
return node ;
31
33
}
32
34
33
35
removeFromBeginning ( ) {
34
36
if ( ! this . head ) {
35
- this . tail = null ;
36
37
return null ;
37
38
}
38
39
if ( this . head . next === null ) {
39
40
this . tail = this . head ;
40
41
}
41
42
const node = this . head ;
42
43
this . head = this . head . next ;
44
+ this . size -= 1 ;
43
45
return node ;
44
46
}
45
47
@@ -57,6 +59,7 @@ class LinkedList {
57
59
58
60
const node = this . tail . next ;
59
61
this . tail . next = null ;
62
+ this . size -= 1 ;
60
63
return node ;
61
64
}
62
65
@@ -108,8 +111,10 @@ class LinkedList {
108
111
count -= 1 ;
109
112
}
110
113
111
- previous . next = new Node ( element , previous . next ) ;
112
- return null ;
114
+ const node = new Node ( element , previous . next ) ;
115
+ previous . next = node ;
116
+ this . size += 1 ;
117
+ return node ;
113
118
}
114
119
115
120
removeAt ( index ) {
@@ -133,21 +138,18 @@ class LinkedList {
133
138
134
139
const node = address ;
135
140
previous . next = address . next . next ;
141
+ this . size -= 1 ;
136
142
return node ;
137
143
}
138
144
139
145
length ( ) {
140
- let address = this . head ;
141
- let count = 0 ;
142
- while ( address ) {
143
- count += 1 ;
144
- address = address . next ;
145
- }
146
- return count ;
146
+ return this . size ;
147
147
}
148
148
149
149
delete ( ) {
150
150
this . head = null ;
151
+ this . tail = this . head ;
152
+ this . size = 0 ;
151
153
}
152
154
}
153
155
You can’t perform that action at this time.
0 commit comments