File tree Expand file tree Collapse file tree 2 files changed +34
-6
lines changed Expand file tree Collapse file tree 2 files changed +34
-6
lines changed Original file line number Diff line number Diff line change 1+ const LinkedList = require ( './linkedlist' ) ;
2+
3+ LinkedList . prototype . findKthToLast = function ( k ) {
4+ let length = 0 ;
5+ for ( let n = this . head ; n ; n = n . next ) { length ++ ; }
6+
7+ if ( k < 1 || k > length ) {
8+ return null ;
9+ }
10+
11+ let node = this . head ;
12+ for ( let i = 0 ; i < length - k ; i ++ ) { node = node . next ; }
13+ return node . data ;
14+ } ;
15+
16+ let list = new LinkedList ( ) ;
17+ list . add ( 4 ) ;
18+ list . add ( 3 ) ;
19+ list . add ( 2 ) ;
20+ list . add ( 1 ) ;
21+
22+ console . log ( list . toString ( ) ) ; //
23+
24+ console . log ( list . findKthToLast ( 0 ) ) ; // null
25+ console . log ( list . findKthToLast ( 1 ) ) ; // 4
26+ console . log ( list . findKthToLast ( 2 ) ) ; // 3
27+ console . log ( list . findKthToLast ( 3 ) ) ; // 2
28+ console . log ( list . findKthToLast ( 4 ) ) ; // 1
29+ console . log ( list . findKthToLast ( 5 ) ) ; // null
Original file line number Diff line number Diff line change 1- let LinkedList = require ( './linkedlist' ) ;
1+ const LinkedList = require ( './linkedlist' ) ;
22
3+ // O(n)
34LinkedList . prototype . dedub = function ( ) {
45 let map = new Map ( ) ;
5- let n = this . head ;
6- map . set ( n . data , 1 ) ;
6+ map . set ( this . head . data , 1 ) ;
77
8- while ( n && n . next ) {
8+ for ( let n = this . head ; n && n . next ; n = n . next ) {
99 let data = n . next . data ;
1010 map . set ( data , 1 ) ;
1111
1212 if ( map . get ( data ) ) {
1313 n . next = n . next . next ;
1414 }
15-
16- n = n . next ;
1715 }
1816} ;
1917
18+ // O(n^2)
2019LinkedList . prototype . dedub2 = function ( ) {
2120 for ( let c = this . head ; c ; c = c . next ) {
2221 for ( let n = c ; n && n . next ; n = n . next ) {
You can’t perform that action at this time.
0 commit comments