File tree Expand file tree Collapse file tree 2 files changed +39
-16
lines changed
Data-Structures/Linked-List Expand file tree Collapse file tree 2 files changed +39
-16
lines changed Original file line number Diff line number Diff line change 11/**
2- * A LinkedList based solution for Detect a Cycle in a list
2+ * A LinkedList based solution for Detecting a Cycle in a list.
33 * https://en.wikipedia.org/wiki/Cycle_detection
44 */
55
6- function main ( ) {
6+ function detectCycle ( head ) {
77 /*
88 Problem Statement:
99 Given head, the head of a linked list, determine if the linked list has a cycle in it.
10-
11- Note:
12- * While Solving the problem in given link below, don't use main() function.
13- * Just use only the code inside main() function.
14- * The purpose of using main() function here is to avoid global variables.
15-
1610 Link for the Problem: https://leetcode.com/problems/linked-list-cycle/
1711 */
18- const head = '' // Reference to head is given in the problem. So please ignore this line
19- let fast = head
20- let slow = head
12+ if ( ! head ) { return false }
2113
22- while ( fast != null && fast . next != null && slow != null ) {
14+ let slow = head
15+ let fast = head . next
16+ while ( fast && fast . next ) {
17+ if ( fast === slow ) { return true }
2318 fast = fast . next . next
2419 slow = slow . next
25- if ( fast === slow ) {
26- return true
27- }
2820 }
2921 return false
3022}
3123
32- main ( )
24+ export { detectCycle }
Original file line number Diff line number Diff line change 1+ import { detectCycle } from '../CycleDetection'
2+ import { Node } from '../SinglyLinkedList'
3+
4+ describe ( 'Detect Cycle' , ( ) => {
5+ it ( 'should detect loop and return true' , ( ) => {
6+ // Creating list and making a loop
7+ const headNode = new Node ( 10 )
8+ headNode . next = new Node ( 20 )
9+ headNode . next . next = new Node ( 30 )
10+ headNode . next . next . next = new Node ( 40 )
11+ headNode . next . next . next . next = headNode
12+ expect ( detectCycle ( headNode ) ) . toEqual ( true )
13+ } )
14+
15+ it ( 'should not detect a loop and return false' , ( ) => {
16+ // Case 0: When head is null, there is no loop.
17+ expect ( detectCycle ( null ) ) . toEqual ( false )
18+ const headNode = new Node ( 10 )
19+
20+ // Case 1: List with single node doesn't have any loop
21+ expect ( detectCycle ( headNode ) ) . toEqual ( false )
22+
23+ headNode . next = new Node ( 20 )
24+ headNode . next . next = new Node ( 30 )
25+ headNode . next . next . next = new Node ( 40 )
26+ headNode . next . next . next . next = new Node ( 50 )
27+
28+ // Case 2: List not having any loops
29+ expect ( detectCycle ( headNode ) ) . toEqual ( false )
30+ } )
31+ } )
You can’t perform that action at this time.
0 commit comments