File tree Expand file tree Collapse file tree 1 file changed +20
-16
lines changed
src/_DataStructures_/LinkedList Expand file tree Collapse file tree 1 file changed +20
-16
lines changed Original file line number Diff line number Diff line change @@ -2,36 +2,42 @@ class Node {
22 constructor ( data , next ) {
33 this . data = data ;
44 this . next = next ;
5+ this . length = 0 ;
56 }
67}
78
89class LinkedList {
910 constructor ( ) {
1011 this . head = null ;
12+ this . tail = null ;
1113 }
1214
1315 addAtBeginning ( element ) {
1416 this . head = new Node ( element , this . head ) ;
17+ if ( ! this . tail ) {
18+ this . tail = this . head ;
19+ }
20+ return this . head ;
1521 }
1622
1723 addAtEnd ( element ) {
18- const node = new Node ( element , null ) ;
19-
2024 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 ) ;
2826 }
27+ const node = new Node ( element , null ) ;
28+ this . tail . next = node ;
29+ this . tail = node ;
30+ return node ;
2931 }
3032
3133 removeFromBeginning ( ) {
3234 if ( ! this . head ) {
35+ this . tail = null ;
3336 return null ;
3437 }
38+ if ( this . head . next === null ) {
39+ this . tail = this . head ;
40+ }
3541 const node = this . head ;
3642 this . head = this . head . next ;
3743 return node ;
@@ -47,8 +53,10 @@ class LinkedList {
4753 address = address . next ;
4854 }
4955
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 ;
5260 return node ;
5361 }
5462
@@ -63,11 +71,7 @@ class LinkedList {
6371 if ( ! this . head ) {
6472 return null ;
6573 }
66- let address = this . head ;
67- while ( address . next ) {
68- address = address . next ;
69- }
70- return address ;
74+ return this . tail ;
7175 }
7276
7377 getAt ( index ) {
You can’t perform that action at this time.
0 commit comments