Posts Merge K sorted linked lists (geeksforgeeks - SDE Sheet)
Post
Cancel

Merge K sorted linked lists (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given an array of sorted linked lists of different sizes. The task is to merge them in such a way that after merging they will be a single sorted linked list.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {

    Node mergeKLists(List<Node> arr) {

        int n = arr.size();

        if(n == 0)
            return null;

        if(n == 1)
            return arr.get(0);

        Node last = arr.get(n-1);
        arr.remove(n-1);

        Node rest = mergeKLists(arr);

        return sortedMerge(last, rest);

    }

    Node sortedMerge(Node head1, Node head2) {

        Node h1 = head1;
        Node h2 = head2;

        Node dummyHead = new Node(0);
        Node tail = dummyHead;

        while (h1 != null && h2 != null) {

            Node temp = null;

            if (h1.data < h2.data) {
                temp = h1;
                h1 = h1.next;
            } else {
                temp = h2;
                h2 = h2.next;
            }

            temp.next = null;

            tail.next = temp;
            tail = tail.next;
        }

        if (h1 != null)
            tail.next = h1;
        else
            tail.next = h2;

        return dummyHead.next;

    }

}
This post is licensed under CC BY 4.0 by the author.