Repository: TheAlgorithms/Java
Pull request #5995 (2024-10-25 12:34:06)

refactor: Enhance docs, add tests in MergeKSortedLinkedList
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [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/5995?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 `90.47619%` with `2 lines` in your changes missing coverage. Please review.
> Project coverage is 68.09%. Comparing base [(`5246f63`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/5246f635797194f5f0d7ac93af61099a5764fa4f?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`da93623`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/da9362302cfa5413ffdfb963fca6c0323ad0c81a?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/5995?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...s/datastructures/lists/MergeKSortedLinkedList.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5995?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fdatastructures%2Flists%2FMergeKSortedLinkedList.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9kYXRhc3RydWN0dXJlcy9saXN0cy9NZXJnZUtTb3J0ZWRMaW5rZWRMaXN0LmphdmE=) | 90.47% | [1 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5995?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    #5995      +/-   ##
============================================
+ Coverage     67.98%   68.09%   +0.11%     
- Complexity     4586     4596      +10     
============================================
  Files           620      620              
  Lines         17116    17128      +12     
  Branches       3305     3308       +3     
============================================
+ Hits          11636    11663      +27     
+ Misses         5035     5020      -15     
  Partials        445      445              
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5995?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).


Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 95805ff4..820b80cd 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -830,6 +830,7 @@
             * lists
               * [CircleLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/CircleLinkedListTest.java)
               * [CreateAndDetectLoopTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoopTest.java)
+              * [MergeKSortedLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedListTest.java)
               * [MergeSortedArrayListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/MergeSortedArrayListTest.java)
               * [MergeSortedSinglyLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedListTest.java)
               * [QuickSortLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/QuickSortLinkedListTest.java)
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java
index 0eac20d2..0f5c5053 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java
@@ -1,51 +1,94 @@
 package com.thealgorithms.datastructures.lists;
 
-import java.util.Arrays;
 import java.util.Comparator;
 import java.util.PriorityQueue;
 
 /**
+ * The MergeKSortedLinkedList class provides a method to merge multiple sorted linked lists
+ * into a single sorted linked list.
+ * This implementation uses a min-heap (priority queue) to efficiently
+ * find the smallest node across all lists, thus optimizing the merge process.
+ *
+ * <p>Example usage:
+ * <pre>
+ * Node list1 = new Node(1, new Node(4, new Node(5)));
+ * Node list2 = new Node(1, new Node(3, new Node(4)));
+ * Node list3 = new Node(2, new Node(6));
+ * Node[] lists = { list1, list2, list3 };
+ *
+ * MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
+ * Node mergedHead = merger.mergeKList(lists, lists.length);
+ * </pre>
+ * </p>
+ *
+ * <p>This class is designed to handle nodes of integer linked lists and can be expanded for additional data types if needed.</p>
+ *
  * @author Arun Pandey (https://github.com/pandeyarun709)
  */
 public class MergeKSortedLinkedList {
 
     /**
-     * This function merge K sorted LinkedList
+     * Merges K sorted linked lists into a single sorted linked list.
      *
-     * @param a array of LinkedList
-     * @param n size of array
-     * @return node
+     * <p>This method uses a priority queue (min-heap) to repeatedly extract the smallest node from the heads of all the lists,
+     * then inserts the next node from that list into the heap. The process continues until all nodes have been processed,
+     * resulting in a fully merged and sorted linked list.</p>
+     *
+     * @param a Array of linked list heads to be merged.
+     * @param n Number of linked lists.
+     * @return Head of the merged sorted linked list.
      */
     Node mergeKList(Node[] a, int n) {
-        // Min Heap
-        PriorityQueue<Node> min = new PriorityQueue<>(Comparator.comparingInt(x -> x.data));
+        if (a == null || n == 0) {
+            return null;
+        }
 
-        // adding head of all linkedList in min heap
-        min.addAll(Arrays.asList(a).subList(0, n));
+        // Min Heap to store nodes based on their values for efficient retrieval of the smallest element.
+        PriorityQueue<Node> minHeap = new PriorityQueue<>(Comparator.comparingInt(x -> x.data));
 
-        // Make new head among smallest heads in K linkedList
-        Node head = min.poll();
-        min.add(head.next);
-        Node curr = head;
+        // Initialize the min-heap with the head of each non-null linked list
+        for (Node node : a) {
+            if (node != null) {
+                minHeap.add(node);
+            }
+        }
+
+        // Start merging process
+        Node head = minHeap.poll(); // Smallest head is the initial head of the merged list
+        if (head != null && head.next != null) {
+            minHeap.add(head.next);
+        }
 
-        // merging LinkedList
-        while (!min.isEmpty()) {
-            Node temp = min.poll();
+        Node curr = head;
+        while (!minHeap.isEmpty()) {
+            Node temp = minHeap.poll();
             curr.next = temp;
             curr = temp;
 
-            // Add Node in min Heap only if temp.next is not null
+            // Add the next node in the current list to the heap if it exists
             if (temp.next != null) {
-                min.add(temp.next);
+                minHeap.add(temp.next);
             }
         }
 
         return head;
     }
 
-    private final class Node {
+    /**
+     * Represents a node in the linked list.
+     */
+    static class Node {
+        int data;
+        Node next;
+
+        Node(int data) {
+            this.data = data;
+            this.next = null;
+        }
 
-        private int data;
-        private Node next;
+        Node(int data, Node next) {
+            this.data = data;
+            this.next = next;
+        }
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedListTest.java
new file mode 100644
index 00000000..99a89011
--- /dev/null
+++ b/src/test/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedListTest.java
@@ -0,0 +1,93 @@
+package com.thealgorithms.datastructures.lists;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+import com.thealgorithms.datastructures.lists.MergeKSortedLinkedList.Node;
+import java.util.Arrays;
+import org.junit.jupiter.api.Test;
+
+class MergeKSortedLinkedListTest {
+
+    @Test
+    void testMergeKLists() {
+        Node list1 = new Node(1, new Node(4, new Node(5)));
+        Node list2 = new Node(1, new Node(3, new Node(4)));
+        Node list3 = new Node(2, new Node(6));
+        Node[] lists = {list1, list2, list3};
+
+        MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
+        Node mergedHead = merger.mergeKList(lists, lists.length);
+
+        int[] expectedValues = {1, 1, 2, 3, 4, 4, 5, 6};
+        int[] actualValues = getListValues(mergedHead);
+        assertArrayEquals(expectedValues, actualValues, "Merged list values do not match the expected sorted order.");
+    }
+
+    @Test
+    void testMergeEmptyLists() {
+        Node[] lists = {null, null, null};
+
+        MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
+        Node mergedHead = merger.mergeKList(lists, lists.length);
+
+        assertNull(mergedHead, "Merged list should be null when all input lists are empty.");
+    }
+
+    @Test
+    void testMergeSingleList() {
+        Node list1 = new Node(1, new Node(3, new Node(5)));
+        Node[] lists = {list1};
+
+        MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
+        Node mergedHead = merger.mergeKList(lists, lists.length);
+
+        int[] expectedValues = {1, 3, 5};
+        int[] actualValues = getListValues(mergedHead);
+        assertArrayEquals(expectedValues, actualValues, "Merged list should match the single input list when only one list is provided.");
+    }
+
+    @Test
+    void testMergeListsOfDifferentLengths() {
+        Node list1 = new Node(1, new Node(3, new Node(5)));
+        Node list2 = new Node(2, new Node(4));
+        Node list3 = new Node(6);
+        Node[] lists = {list1, list2, list3};
+
+        MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
+        Node mergedHead = merger.mergeKList(lists, lists.length);
+
+        int[] expectedValues = {1, 2, 3, 4, 5, 6};
+        int[] actualValues = getListValues(mergedHead);
+        assertArrayEquals(expectedValues, actualValues, "Merged list values do not match expected sorted order for lists of different lengths.");
+    }
+
+    @Test
+    void testMergeSingleElementLists() {
+        Node list1 = new Node(1);
+        Node list2 = new Node(3);
+        Node list3 = new Node(2);
+        Node[] lists = {list1, list2, list3};
+
+        MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
+        Node mergedHead = merger.mergeKList(lists, lists.length);
+
+        int[] expectedValues = {1, 2, 3};
+        int[] actualValues = getListValues(mergedHead);
+        assertArrayEquals(expectedValues, actualValues, "Merged list values do not match expected sorted order for single-element lists.");
+    }
+
+    /**
+     * Helper method to extract values from the linked list into an array for assertion.
+     */
+    private int[] getListValues(Node head) {
+        int[] values = new int[100]; // assuming max length for simplicity
+        int i = 0;
+        Node curr = head;
+        while (curr != null) {
+            values[i++] = curr.data;
+            curr = curr.next;
+        }
+        return Arrays.copyOf(values, i); // return only filled part
+    }
+}