File tree 2 files changed +45
-1
lines changed
src/_DataStructures_/LinkedList/loop-in-list
2 files changed +45
-1
lines changed Original file line number Diff line number Diff line change 1
1
// Floyd’s Cycle-Finding Algorithm
2
2
3
- function detechLoop ( linkedList ) {
3
+ function detectLoop ( linkedList ) {
4
4
let slow = linkedList . getFirst ( ) ;
5
5
let fast = linkedList . getFirst ( ) ;
6
6
@@ -14,3 +14,7 @@ function detechLoop(linkedList) {
14
14
}
15
15
return false ;
16
16
}
17
+
18
+ module . exports = {
19
+ detectLoop,
20
+ } ;
Original file line number Diff line number Diff line change
1
+ const { LinkedList } = require ( '../index' ) ;
2
+ const { detectLoop } = require ( '.' ) ;
3
+
4
+ describe ( 'Loop a LinkedList' , ( ) => {
5
+ let loopList = null ;
6
+ let last = null ;
7
+ beforeEach ( ( ) => {
8
+ loopList = new LinkedList ( ) ;
9
+ loopList . addAtBeginning ( '1' ) ;
10
+ loopList . addAtEnd ( '2' ) ;
11
+ loopList . addAtEnd ( '3' ) ;
12
+ loopList . addAtEnd ( '4' ) ;
13
+ loopList . addAtEnd ( '5' ) ;
14
+ // Create loop in list
15
+ last = loopList . getLast ( ) ;
16
+ last . next = loopList . getFirst ( ) ;
17
+ } ) ;
18
+
19
+ it ( 'Should break for empty list' , ( ) => {
20
+ loopList . delete ( ) ;
21
+ expect ( ( ) => detectLoop ( loopList ) ) . toThrow ( TypeError ) ;
22
+ } ) ;
23
+
24
+ it ( 'Should return `true` when looping list' , ( ) => {
25
+ expect ( detectLoop ( loopList ) ) . toEqual ( true ) ;
26
+ } ) ;
27
+
28
+ it ( 'Should return `false` for non loop list' , ( ) => {
29
+ last . next = null ; // remove loop in list
30
+ expect ( detectLoop ( loopList ) ) . toEqual ( false ) ;
31
+ } ) ;
32
+
33
+ it ( 'Should return `false` for non loop list' , ( ) => {
34
+ const list = new LinkedList ( ) ;
35
+ list . addAtBeginning ( '1' ) ;
36
+ list . addAtEnd ( '1' ) ;
37
+ list . addAtEnd ( '1' ) ;
38
+ expect ( detectLoop ( list ) ) . toEqual ( false ) ;
39
+ } ) ;
40
+ } ) ;
You can’t perform that action at this time.
0 commit comments