@@ -8,32 +8,40 @@ class Node {
8
8
class LinkedList {
9
9
constructor ( ) {
10
10
this . head = null ;
11
+ this . tail = null ;
12
+ this . size = 0 ;
11
13
}
12
14
13
15
addAtBeginning ( element ) {
14
16
this . head = new Node ( element , this . head ) ;
17
+ if ( ! this . tail ) {
18
+ this . tail = this . head ;
19
+ }
20
+ this . size += 1 ;
21
+ return this . head ;
15
22
}
16
23
17
24
addAtEnd ( element ) {
18
- const node = new Node ( element , null ) ;
19
-
20
25
if ( ! this . head ) {
21
- this . head = node ;
22
- } else {
23
- let address = this . head ;
24
- while ( address . next ) {
25
- address = address . next ;
26
- }
27
- address . next = node ;
26
+ return this . addAtBeginning ( element ) ;
28
27
}
28
+ const node = new Node ( element , null ) ;
29
+ this . tail . next = node ;
30
+ this . tail = node ;
31
+ this . size += 1 ;
32
+ return node ;
29
33
}
30
34
31
35
removeFromBeginning ( ) {
32
36
if ( ! this . head ) {
33
37
return null ;
34
38
}
39
+ if ( this . head . next === null ) {
40
+ this . tail = this . head ;
41
+ }
35
42
const node = this . head ;
36
43
this . head = this . head . next ;
44
+ this . size -= 1 ;
37
45
return node ;
38
46
}
39
47
@@ -47,8 +55,11 @@ class LinkedList {
47
55
address = address . next ;
48
56
}
49
57
50
- const node = address . next ;
51
- address . next = null ;
58
+ this . tail = address ;
59
+
60
+ const node = this . tail . next ;
61
+ this . tail . next = null ;
62
+ this . size -= 1 ;
52
63
return node ;
53
64
}
54
65
@@ -63,11 +74,7 @@ class LinkedList {
63
74
if ( ! this . head ) {
64
75
return null ;
65
76
}
66
- let address = this . head ;
67
- while ( address . next ) {
68
- address = address . next ;
69
- }
70
- return address ;
77
+ return this . tail ;
71
78
}
72
79
73
80
getAt ( index ) {
@@ -104,8 +111,10 @@ class LinkedList {
104
111
count -= 1 ;
105
112
}
106
113
107
- previous . next = new Node ( element , previous . next ) ;
108
- return null ;
114
+ const node = new Node ( element , previous . next ) ;
115
+ previous . next = node ;
116
+ this . size += 1 ;
117
+ return node ;
109
118
}
110
119
111
120
removeAt ( index ) {
@@ -129,21 +138,18 @@ class LinkedList {
129
138
130
139
const node = address ;
131
140
previous . next = address . next . next ;
141
+ this . size -= 1 ;
132
142
return node ;
133
143
}
134
144
135
145
length ( ) {
136
- let address = this . head ;
137
- let count = 0 ;
138
- while ( address ) {
139
- count += 1 ;
140
- address = address . next ;
141
- }
142
- return count ;
146
+ return this . size ;
143
147
}
144
148
145
149
delete ( ) {
146
150
this . head = null ;
151
+ this . tail = this . head ;
152
+ this . size = 0 ;
147
153
}
148
154
}
149
155
0 commit comments