File tree Expand file tree Collapse file tree 1 file changed +22
-17
lines changed
chapter02/2.8 - Loop Detection Expand file tree Collapse file tree 1 file changed +22
-17
lines changed Original file line number Diff line number Diff line change 11var LinkedList = require ( './../util/LinkedList' ) ;
22
33var loopDetection = ( head ) => {
4- var hare = head ;
5- var tortoise = head ;
6- while ( hare !== null ) {
7- tortoise = tortoise . next ;
8- hare = hare . next ;
9- if ( hare === tortoise && hare !== head . next ) {
10- return true ;
11- }
12- if ( hare !== null ) {
13- hare = hare . next ;
14- if ( hare === tortoise ) {
15- return true ;
16- }
17- }
4+ // The null checking code will handle lists with no loops.
5+ if ( ! head || ! head . next ) return null
6+
7+ var hare = head
8+ var tortoise = head
9+
10+ do {
11+ hare = hare . next
12+ tortoise = tortoise . next
13+ if ( ! hare || ! hare . next ) return null
14+ hare = hare . next
15+ } while ( hare !== tortoise )
16+
17+ tortoise = head
18+
19+ while ( hare !== tortoise ) {
20+ hare = hare . next
21+ tortoise = tortoise . next
1822 }
19- return false ;
23+
24+ return hare
2025} ;
2126
2227/* TEST */
@@ -36,7 +41,7 @@ d.next = e;
3641e . next = f ;
3742f . next = c ;
3843
39- console . log ( loopDetection ( a ) , true ) ;
44+ console . log ( loopDetection ( a ) === c , true ) ;
4045
4146var A = new LinkedList ( ) ;
4247var B = new LinkedList ( ) ;
@@ -51,4 +56,4 @@ C.next = D;
5156D . next = E ;
5257E . next = F ;
5358
54- console . log ( loopDetection ( A ) , false ) ;
59+ console . log ( loopDetection ( A ) === null , false ) ;
You can’t perform that action at this time.
0 commit comments