|
| 1 | +package com.thealgorithms.datastructures.lists; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.*; |
| 4 | +import org.junit.jupiter.api.BeforeEach; |
| 5 | +import org.junit.jupiter.api.Test; |
| 6 | + |
| 7 | +public class CreateAndDetectLoopTest { |
| 8 | + |
| 9 | + private CreateAndDetectLoop.Node head; |
| 10 | + |
| 11 | + @BeforeEach |
| 12 | + void setUp() { |
| 13 | + // Create a linked list: 1 -> 2 -> 3 -> 4 -> 5 -> 6 |
| 14 | + head = new CreateAndDetectLoop.Node(1); |
| 15 | + CreateAndDetectLoop.Node second = new CreateAndDetectLoop.Node(2); |
| 16 | + CreateAndDetectLoop.Node third = new CreateAndDetectLoop.Node(3); |
| 17 | + CreateAndDetectLoop.Node fourth = new CreateAndDetectLoop.Node(4); |
| 18 | + CreateAndDetectLoop.Node fifth = new CreateAndDetectLoop.Node(5); |
| 19 | + CreateAndDetectLoop.Node sixth = new CreateAndDetectLoop.Node(6); |
| 20 | + |
| 21 | + head.next = second; |
| 22 | + second.next = third; |
| 23 | + third.next = fourth; |
| 24 | + fourth.next = fifth; |
| 25 | + fifth.next = sixth; |
| 26 | + } |
| 27 | + |
| 28 | + @Test |
| 29 | + void testDetectLoop_NoLoop() { |
| 30 | + // Test when no loop exists |
| 31 | + assertFalse(CreateAndDetectLoop.detectLoop(head), "There should be no loop."); |
| 32 | + } |
| 33 | + |
| 34 | + @Test |
| 35 | + void testCreateAndDetectLoop_LoopExists() { |
| 36 | + // Create a loop between position 2 (node with value 2) and position 5 (node with value 5) |
| 37 | + CreateAndDetectLoop.createLoop(head, 2, 5); |
| 38 | + |
| 39 | + // Now test if the loop is detected |
| 40 | + assertTrue(CreateAndDetectLoop.detectLoop(head), "A loop should be detected."); |
| 41 | + } |
| 42 | + |
| 43 | + @Test |
| 44 | + void testCreateLoop_InvalidPosition() { |
| 45 | + // Create loop with invalid positions |
| 46 | + CreateAndDetectLoop.createLoop(head, 0, 0); |
| 47 | + |
| 48 | + // Ensure no loop was created |
| 49 | + assertFalse(CreateAndDetectLoop.detectLoop(head), "There should be no loop with invalid positions."); |
| 50 | + } |
| 51 | + |
| 52 | + @Test |
| 53 | + void testCreateLoop_SelfLoop() { |
| 54 | + // Create a self-loop at position 3 (node with value 3) |
| 55 | + CreateAndDetectLoop.createLoop(head, 3, 3); |
| 56 | + |
| 57 | + // Test if the self-loop is detected |
| 58 | + assertTrue(CreateAndDetectLoop.detectLoop(head), "A self-loop should be detected."); |
| 59 | + } |
| 60 | + |
| 61 | + @Test |
| 62 | + void testCreateLoop_NoChangeForNonExistentPositions() { |
| 63 | + // Create a loop with positions that don't exist in the linked list |
| 64 | + CreateAndDetectLoop.createLoop(head, 10, 20); |
| 65 | + |
| 66 | + // Ensure no loop was created |
| 67 | + assertFalse(CreateAndDetectLoop.detectLoop(head), "No loop should be created if positions are out of bounds."); |
| 68 | + } |
| 69 | +} |
| 70 | + |
0 commit comments