File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed
src/_DataStructures_/LinkedList/element-from-last Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ const { getElementFromlast } = require ( '.' ) ;
2+ const { LinkedList } = require ( '../index' ) ;
3+
4+ describe ( 'Find the middle node of a LinkedList' , ( ) => {
5+ let list = null ;
6+ beforeEach ( ( ) => {
7+ list = new LinkedList ( ) ;
8+ list . addAtBeginning ( 'Hello' ) ;
9+ list . addAtEnd ( 'World!' ) ;
10+ list . addAtEnd ( 'Welcome' ) ;
11+ list . addAtEnd ( 'to' ) ;
12+ list . addAtEnd ( 'the' ) ;
13+ list . addAtEnd ( 'world' ) ;
14+ list . addAtEnd ( 'of' ) ;
15+ list . addAtEnd ( 'JavaScript' ) ;
16+ } ) ;
17+
18+ it ( 'Should return `null` for empty list' , ( ) => {
19+ list . delete ( ) ;
20+ expect ( getElementFromlast ( list , 10 ) ) . toEqual ( null ) ;
21+ } ) ;
22+
23+ it ( 'Should return `world` as 3rd from last of the list' , ( ) => {
24+ expect ( getElementFromlast ( list , 3 ) . data ) . toEqual ( 'world' ) ;
25+ } ) ;
26+
27+ it ( 'Should return `Welcome` as 6th from last of the list' , ( ) => {
28+ expect ( getElementFromlast ( list , 6 ) . data ) . toEqual ( 'Welcome' ) ;
29+ } ) ;
30+ } ) ;
Original file line number Diff line number Diff line change 1+ function getElementFromlast ( linkedList , index ) {
2+ let normal = linkedList . getFirst ( ) ;
3+ let nth = linkedList . getFirst ( ) ;
4+ let count = 0 ;
5+
6+ if ( ! normal ) {
7+ return null ;
8+ }
9+
10+ while ( normal ) {
11+ if ( count >= index ) {
12+ nth = nth . next ;
13+ }
14+ normal = normal . next ;
15+ count += 1 ;
16+ }
17+ return nth ;
18+ }
19+
20+ module . exports = {
21+ getElementFromlast,
22+ } ;
You can’t perform that action at this time.
0 commit comments