1
- import { createSinglyLinkedListNode } from "../testUtilities/LinkedList" ;
2
- import { SinglyLinkedListNode } from "../types/LinkedList" ;
1
+ import {
2
+ createSinglyLinkedListNode ,
3
+ getNthNode
4
+ } from "../testUtilities/LinkedList" ;
3
5
import hasCycle from "./linkedListCycle" ;
4
6
5
7
describe ( "141. Linked List Cycle" , ( ) => {
@@ -10,22 +12,13 @@ describe("141. Linked List Cycle", () => {
10
12
] ) ;
11
13
12
14
for ( const [ [ values , cycleStart ] , expected ] of TEST_CASES ) {
13
- it ( `returns ${ expected } when called with [${ values } ] (cycle starts from ${ cycleStart } )` , ( ) => {
14
- const head = createSinglyLinkedListNode ( values ) ;
15
+ it ( `returns ${ expected } when called with [${ values } ] ${
16
+ cycleStart === - 1 ? "(no cycle)" : `(cycle starts from ${ cycleStart } )`
17
+ } `, ( ) => {
18
+ const head = createSinglyLinkedListNode ( values ) ! ;
15
19
16
- let node = head ;
17
- let cycleStartNode : SinglyLinkedListNode < number > | null = null ;
18
-
19
- for ( const i of values . keys ( ) ) {
20
- if ( i === cycleStart ) {
21
- cycleStartNode = node ;
22
- }
23
-
24
- if ( i === values . length - 1 ) {
25
- node ! . next = cycleStartNode ;
26
- }
27
-
28
- node = node ! . next ;
20
+ if ( cycleStart !== - 1 ) {
21
+ getNthNode ( head , - 1 ) . next = getNthNode ( head , cycleStart ) ;
29
22
}
30
23
31
24
expect ( hasCycle ( head ) ) . toBe ( expected ) ;
0 commit comments