File tree 1 file changed +20
-16
lines changed
src/_DataStructures_/LinkedList
1 file changed +20
-16
lines changed Original file line number Diff line number Diff line change @@ -2,36 +2,42 @@ class Node {
2
2
constructor ( data , next ) {
3
3
this . data = data ;
4
4
this . next = next ;
5
+ this . length = 0 ;
5
6
}
6
7
}
7
8
8
9
class LinkedList {
9
10
constructor ( ) {
10
11
this . head = null ;
12
+ this . tail = null ;
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
+ return this . head ;
15
21
}
16
22
17
23
addAtEnd ( element ) {
18
- const node = new Node ( element , null ) ;
19
-
20
24
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 ;
25
+ return this . addAtBeginning ( element ) ;
28
26
}
27
+ const node = new Node ( element , null ) ;
28
+ this . tail . next = node ;
29
+ this . tail = node ;
30
+ return node ;
29
31
}
30
32
31
33
removeFromBeginning ( ) {
32
34
if ( ! this . head ) {
35
+ this . tail = null ;
33
36
return null ;
34
37
}
38
+ if ( this . head . next === null ) {
39
+ this . tail = this . head ;
40
+ }
35
41
const node = this . head ;
36
42
this . head = this . head . next ;
37
43
return node ;
@@ -47,8 +53,10 @@ class LinkedList {
47
53
address = address . next ;
48
54
}
49
55
50
- const node = address . next ;
51
- address . next = null ;
56
+ this . tail = address ;
57
+
58
+ const node = this . tail . next ;
59
+ this . tail . next = null ;
52
60
return node ;
53
61
}
54
62
@@ -63,11 +71,7 @@ class LinkedList {
63
71
if ( ! this . head ) {
64
72
return null ;
65
73
}
66
- let address = this . head ;
67
- while ( address . next ) {
68
- address = address . next ;
69
- }
70
- return address ;
74
+ return this . tail ;
71
75
}
72
76
73
77
getAt ( index ) {
You can’t perform that action at this time.
0 commit comments