Repository: TheAlgorithms/Java
Pull request #5561 (2024-10-03 20:12:56)

updated CreateAndDetectLoop with test

### Above algorithm helps to find the length of loop in linkedlist

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5561?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `0%` with `40 lines` in your changes missing coverage. Please review.
> Project coverage is 52.83%. Comparing base [(`be8df21`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/be8df2188c716389de5150487c0862b80d88bd4e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`334bdbb`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/334bdbb6a624dd3d5ecb654acf4be6cef76d6118?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5561?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...ithms/datastructures/lists/LengthOfLoopInList.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5561?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fdatastructures%2Flists%2FLengthOfLoopInList.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9kYXRhc3RydWN0dXJlcy9saXN0cy9MZW5ndGhPZkxvb3BJbkxpc3QuamF2YQ==) | 0.00% | [40 Missing :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5561?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5561      +/-   ##
============================================
- Coverage     52.95%   52.83%   -0.12%     
- Complexity     3309     3311       +2     
============================================
  Files           529      530       +1     
  Lines         15343    15383      +40     
  Branches       2925     2929       +4     
============================================
+ Hits           8125     8128       +3     
- Misses         6882     6921      +39     
+ Partials        336      334       -2     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5561?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

siriak: It's already present here https://github.com/TheAlgorithms/Java/blob/b61c54797babbe46825586894d69715d8947d559/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java#L5. Please improve the existing implementation (remove main, add tests, etc.)
albinsabu2023: bro i have added unit test .But struggling to figure out the  issues with clang and build .Can you help me with that. In my system I have installed jdk22 is that an issue ?cause i seen v21 in pom

albinsabu2023: added unit test and fixed build issues can you please help with lint issue

@siriak 
albinsabu2023: sorry for this much commit :) ,As I am a beginner I took Lot of time to figure out the issues .Hopefully this will be good to go 
can you please review and add hacktoberfest and hacktoberfest-accepted label with this pr. @siriak 
albinsabu2023: Am i missing something ? Cuz I didnt get any response @arindam89  @siriak  @BurkHufnagel 

Patch:
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java b/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java
index 441c9570..49115b2d 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java
@@ -1,63 +1,66 @@
 package com.thealgorithms.datastructures.lists;
 
-import java.util.Scanner;
-
 public final class CreateAndDetectLoop {
+
+    // Node class representing a single node in the linked list
     private CreateAndDetectLoop() {
+        throw new UnsupportedOperationException("Utility class");
     }
+    static final class Node {
+        int data;
+        Node next;
 
-    /**
-     * Prints the linked list.
-     *
-     * @param	head	head node of the linked list
-     */
-    static void printList(Node head) {
-        Node cur = head;
-
-        while (cur != null) {
-            System.out.print(cur.value + " ");
-            cur = cur.next;
+        Node(int data) {
+            this.data = data;
+            next = null;
         }
     }
 
-    /**
-     * Creates a loop in the linked list.
-     *
-     * @see
-     * 	<a href="https://www.geeksforgeeks.org/make-loop-k-th-position-linked-list/">
-     * GeeksForGeeks: Make a loop at K-th position</a>
-     * @param	head	head node of the linked list
-     * @param	k	position of node where loop is to be created
+    // Method to create a loop between two specific positions in the linked list
+    /*
+     *  Test case that shows the Cycle(loop) in a LinkedList
+     *  Let's take this linked list:
+     *  1->2->3->4->5->6
+     *     \______/
+     *   In this linked list we can see there is a cycle.
+     *   we can create loop by calling createLoop function in main after creating LL
+     *   createLoop(head,2,5);
+     *  to detect there is loop or not we can call detectloop function in main
+     *  detectloop(head);
      */
-    static void createLoop(Node head, int k) {
-        if (head == null) {
+
+    static void createLoop(Node head, int position1, int position2) {
+        if (position1 == 0 || position2 == 0) {
             return;
         }
-        Node temp = head;
-        int count = 1;
-        while (count < k) { // Traverse the list till the kth node
-            temp = temp.next;
-            count++;
-        }
 
-        Node connectedPoint = temp;
+        Node node1 = head;
+        Node node2 = head;
 
-        while (temp.next != null) { // Traverse remaining nodes
-            temp = temp.next;
+        int count1 = 1;
+        int count2 = 1;
+        // Traverse to find node at position1
+        while (count1 < position1 && node1 != null) {
+            node1 = node1.next;
+            count1++;
         }
 
-        temp.next = connectedPoint; // Connect last node to k-th element
-    }
+        // Traverse to find node at position2
+        while (count2 < position2 && node2 != null) {
+            node2 = node2.next;
+            count2++;
+        }
 
+        // Create a loop by connecting node2's next to node1
+        if (node1 != null && node2 != null) {
+            node2.next = node1;
+        }
+    }
+    // Method to detect a loop in the linked list
     /**
      * Detects the presence of a loop in the linked list.
      *
-     * @see
-     * 	<a href="https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare">
-     * Floyd's Cycle Detection Algorithm</a>
-     *
-     * @param head the head node of the linked list
-     *
+     * @see <a href="https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare">Floyd's Cycle Detection Algorithm</a>
      * @return true if loop exists else false
      */
     static boolean detectLoop(Node head) {
@@ -67,40 +70,10 @@ public final class CreateAndDetectLoop {
         while (fptr != null && fptr.next != null) {
             sptr = sptr.next;
             fptr = fptr.next.next;
-            if (fptr == sptr) {
+            if (sptr == fptr) {
                 return true;
             }
         }
-
         return false;
     }
-
-    public static void main(String[] args) {
-        SinglyLinkedList singlyLinkedList = new SinglyLinkedList();
-        Scanner sc = new Scanner(System.in);
-
-        System.out.println("Enter the number of elements to be inserted: ");
-        int n = sc.nextInt();
-        System.out.printf("Enter the %d elements: %n", n);
-        while (n-- > 0) {
-            singlyLinkedList.insert(sc.nextInt());
-        }
-
-        System.out.print("Given list: ");
-        printList(singlyLinkedList.getHead());
-        System.out.println();
-
-        System.out.println("Enter the location to generate loop: ");
-        int k = sc.nextInt();
-
-        createLoop(singlyLinkedList.getHead(), k);
-
-        if (detectLoop(singlyLinkedList.getHead())) {
-            System.out.println("Loop found");
-        } else {
-            System.out.println("No loop found");
-        }
-
-        sc.close();
-    }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoopTest.java b/src/test/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoopTest.java
new file mode 100644
index 00000000..5e9d4c3a
--- /dev/null
+++ b/src/test/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoopTest.java
@@ -0,0 +1,71 @@
+package com.thealgorithms.datastructures.lists;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class CreateAndDetectLoopTest {
+
+    private CreateAndDetectLoop.Node head;
+
+    @BeforeEach
+    void setUp() {
+        // Create a linked list: 1 -> 2 -> 3 -> 4 -> 5 -> 6
+        head = new CreateAndDetectLoop.Node(1);
+        CreateAndDetectLoop.Node second = new CreateAndDetectLoop.Node(2);
+        CreateAndDetectLoop.Node third = new CreateAndDetectLoop.Node(3);
+        CreateAndDetectLoop.Node fourth = new CreateAndDetectLoop.Node(4);
+        CreateAndDetectLoop.Node fifth = new CreateAndDetectLoop.Node(5);
+        CreateAndDetectLoop.Node sixth = new CreateAndDetectLoop.Node(6);
+
+        head.next = second;
+        second.next = third;
+        third.next = fourth;
+        fourth.next = fifth;
+        fifth.next = sixth;
+    }
+
+    @Test
+    void testDetectLoopNoLoop() {
+        // Test when no loop exists
+        assertFalse(CreateAndDetectLoop.detectLoop(head), "There should be no loop.");
+    }
+
+    @Test
+    void testCreateAndDetectLoopLoopExists() {
+        // Create a loop between position 2 (node with value 2) and position 5 (node with value 5)
+        CreateAndDetectLoop.createLoop(head, 2, 5);
+
+        // Now test if the loop is detected
+        assertTrue(CreateAndDetectLoop.detectLoop(head), "A loop should be detected.");
+    }
+
+    @Test
+    void testCreateLoopInvalidPosition() {
+        // Create loop with invalid positions
+        CreateAndDetectLoop.createLoop(head, 0, 0);
+
+        // Ensure no loop was created
+        assertFalse(CreateAndDetectLoop.detectLoop(head), "There should be no loop with invalid positions.");
+    }
+
+    @Test
+    void testCreateLoopSelfLoop() {
+        // Create a self-loop at position 3 (node with value 3)
+        CreateAndDetectLoop.createLoop(head, 3, 3);
+
+        // Test if the self-loop is detected
+        assertTrue(CreateAndDetectLoop.detectLoop(head), "A self-loop should be detected.");
+    }
+
+    @Test
+    void testCreateLoopNoChangeForNonExistentPositions() {
+        // Create a loop with positions that don't exist in the linked list
+        CreateAndDetectLoop.createLoop(head, 10, 20);
+
+        // Ensure no loop was created
+        assertFalse(CreateAndDetectLoop.detectLoop(head), "No loop should be created if positions are out of bounds.");
+    }
+}