合并 K 个有序链表

119 阅读17分钟

合并 K 个有序链表

给定 K 个大小为 N 的已排序链表,任务是将它们全部合并并保持其排序顺序。

例子:

输入:K = 3,N = 4
list1 = 1->3->5->7->NULL
list2 = 2->4->6->8->NULL
list3 = 0->9->10->11->NULL
输出:0->1->2->3->4->5->6->7->8->9->10->11
按排序顺序合并列表,其中每个元素都大于等于前一个元素。

输入:K = 3,N = 3
list1 = 1->3->7->NULL
list2 = 2->4->8->NULL
list3 = 9->10->11->NULL
输出:1->2->3->4->7->8->9->10->11
按排序顺序合并列表,其中每个元素都大于等于前一个元素。

暴力方法:

一个暴力的解决方案是将结果初始化为第一个列表。然后从第二个列表开始遍历所有列表。将当前遍历列表的每个节点按照排序插入到结果中。

下面是上述方法的实现:

C++

// C++ program to merge k sorted
// arrays of size n each
#include <bits/stdc++.h>
using namespace std;
 
// A Linked List node
struct Node {
    int data;
    Node* next;
};
 
/* Function to print nodes in
   a given linked list */
void printList(Node* node)
{
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
}
 
// The main function that
// takes an array of lists
// arr[0..last] and generates
// the sorted output
Node* mergeKLists(Node* arr[], int last)
{
 
    // Traverse form second list to last
    for (int i = 1; i <= last; i++) {
        while (true) {
            // head of both the lists,
            // 0 and ith list.
            Node *head_0 = arr[0], *head_i = arr[i];
 
            // Break if list ended
            if (head_i == NULL)
                break;
 
            // Smaller than first element
            if (head_0->data >= head_i->data) {
                arr[i] = head_i->next;
                head_i->next = head_0;
                arr[0] = head_i;
            }
            else
                // Traverse the first list
                while (head_0->next != NULL) {
                    // Smaller than next element
                    if (head_0->next->data
                        >= head_i->data) {
                        arr[i] = head_i->next;
                        head_i->next = head_0->next;
                        head_0->next = head_i;
                        break;
                    }
                    // go to next node
                    head_0 = head_0->next;
 
                    // if last node
                    if (head_0->next == NULL) {
                        arr[i] = head_i->next;
                        head_i->next = NULL;
                        head_0->next = head_i;
                        head_0->next->next = NULL;
                        break;
                    }
                }
        }
    }
 
    return arr[0];
}
 
// Utility function to create a new node.
Node* newNode(int data)
{
    struct Node* temp = new Node;
    temp->data = data;
    temp->next = NULL;
    return temp;
}
 
// Driver program to test
// above functions
int main()
{
    // Number of linked lists
    int k = 3;
 
    // Number of elements in each list
    int n = 4;
 
    // an array of pointers storing the
    // head nodes of the linked lists
    Node* arr[k];
 
    arr[0] = newNode(1);
    arr[0]->next = newNode(3);
    arr[0]->next->next = newNode(5);
    arr[0]->next->next->next = newNode(7);
 
    arr[1] = newNode(2);
    arr[1]->next = newNode(4);
    arr[1]->next->next = newNode(6);
    arr[1]->next->next->next = newNode(8);
 
    arr[2] = newNode(0);
    arr[2]->next = newNode(9);
    arr[2]->next->next = newNode(10);
    arr[2]->next->next->next = newNode(11);
 
    // Merge all lists
    Node* head = mergeKLists(arr, k - 1);
 
    printList(head);
 
    return 0;
}

Java

// Java program to merge k sorted
// arrays of size n each
import java.io.*;
 
// A Linked List node
class Node {
    int data;
    Node next;
 
    // Utility function to create a new node.
    Node(int key)
    {
        data = key;
        next = null;
    }
}
class GFG {
 
    static Node head;
    static Node temp;
 
    /* Function to print nodes in
     a given linked list */
    static void printList(Node node)
    {
        while (node != null) {
            System.out.print(node.data + " ");
 
            node = node.next;
        }
        System.out.println();
    }
 
    // The main function that
    // takes an array of lists
    // arr[0..last] and generates
    // the sorted output
    static Node mergeKLists(Node arr[], int last)
    {
 
        // Traverse form second list to last
        for (int i = 1; i <= last; i++) {
            while (true) {
 
                // head of both the lists,
                // 0 and ith list.
                Node head_0 = arr[0];
                Node head_i = arr[i];
 
                // Break if list ended
                if (head_i == null)
                    break;
 
                // Smaller than first element
                if (head_0.data >= head_i.data) {
                    arr[i] = head_i.next;
                    head_i.next = head_0;
                    arr[0] = head_i;
                }
                else {
 
                    // Traverse the first list
                    while (head_0.next != null) {
 
                        // Smaller than next element
                        if (head_0.next.data
                            >= head_i.data) {
                            arr[i] = head_i.next;
                            head_i.next = head_0.next;
                            head_0.next = head_i;
                            break;
                        }
 
                        // go to next node
                        head_0 = head_0.next;
 
                        // if last node
                        if (head_0.next == null) {
                            arr[i] = head_i.next;
                            head_i.next = null;
                            head_0.next = head_i;
                            head_0.next.next = null;
                            break;
                        }
                    }
                }
            }
        }
        return arr[0];
    }
 
    // Driver program to test
    // above functions
    public static void main(String[] args)
    {
 
        // Number of linked lists
        int k = 3;
 
        // Number of elements in each list
        int n = 4;
 
        // an array of pointers storing the
        // head nodes of the linked lists
 
        Node[] arr = new Node[k];
 
        arr[0] = new Node(1);
        arr[0].next = new Node(3);
        arr[0].next.next = new Node(5);
        arr[0].next.next.next = new Node(7);
 
        arr[1] = new Node(2);
        arr[1].next = new Node(4);
        arr[1].next.next = new Node(6);
        arr[1].next.next.next = new Node(8);
 
        arr[2] = new Node(0);
        arr[2].next = new Node(9);
        arr[2].next.next = new Node(10);
        arr[2].next.next.next = new Node(11);
 
        // Merge all lists
        head = mergeKLists(arr, k - 1);
        printList(head);
    }
}
 

Python

# Python3 program to merge k
# sorted arrays of size n each
 
# A Linked List node
 
 
class Node:
 
    def __init__(self, x):
 
        self.data = x
        self.next = None
 
# Function to print nodes in
# a given linked list
 
 
def printList(node):
 
    while (node != None):
        print(node.data,
              end=" ")
        node = node.next
 
# The main function that
# takes an array of lists
# arr[0..last] and generates
# the sorted output
 
 
def mergeKLists(arr, last):
 
    # Traverse form second
    # list to last
    for i in range(1, last + 1):
        while (True):
            # head of both the lists,
            # 0 and ith list.
            head_0 = arr[0]
            head_i = arr[i]
 
            # Break if list ended
            if (head_i == None):
                break
 
            # Smaller than first
            # element
            if (head_0.data >=
                    head_i.data):
                arr[i] = head_i.next
                head_i.next = head_0
                arr[0] = head_i
            else:
                # Traverse the first list
                while (head_0.next != None):
                    # Smaller than next
                    # element
                    if (head_0.next.data >=
                            head_i.data):
                        arr[i] = head_i.next
                        head_i.next = head_0.next
                        head_0.next = head_i
                        break
                    # go to next node
                    head_0 = head_0.next
                    # if last node
                    if (head_0.next == None):
                        arr[i] = head_i.next
                        head_i.next = None
                        head_0.next = head_i
                        head_0.next.next = None
                        break
    return arr[0]
 
 
# Driver code
if __name__ == '__main__':
 
    # Number of linked
    # lists
    k = 3
 
    # Number of elements
    # in each list
    n = 4
 
    # an array of pointers
    # storing the head nodes
    # of the linked lists
    arr = [None for i in range(k)]
 
    arr[0] = Node(1)
    arr[0].next = Node(3)
    arr[0].next.next = Node(5)
    arr[0].next.next.next = Node(7)
 
    arr[1] = Node(2)
    arr[1].next = Node(4)
    arr[1].next.next = Node(6)
    arr[1].next.next.next = Node(8)
 
    arr[2] = Node(0)
    arr[2].next = Node(9)
    arr[2].next.next = Node(10)
    arr[2].next.next.next = Node(11)
 
    # Merge all lists
    head = mergeKLists(arr, k - 1)
 
    printList(head)
 

C#

// C# program to merge k sorted
// arrays of size n each
using System;
 
// A Linked List node
public class Node {
    public int data;
    public Node next;
 
    // Utility function to create a new node.
    public Node(int key)
    {
        data = key;
        next = null;
    }
}
 
public class GFG {
    static Node head;
 
    /* Function to print nodes in
     a given linked list */
    static void printList(Node node)
    {
        while (node != null) {
            Console.Write(node.data + " ");
            node = node.next;
        }
        Console.WriteLine();
    }
 
    // The main function that
    // takes an array of lists
    // arr[0..last] and generates
    // the sorted output
    static Node mergeKLists(Node[] arr, int last)
    {
 
        // Traverse form second list to last
        for (int i = 1; i <= last; i++) {
            while (true) {
 
                // head of both the lists,
                // 0 and ith list.
                Node head_0 = arr[0];
                Node head_i = arr[i];
 
                // Break if list ended
                if (head_i == null)
                    break;
 
                // Smaller than first element
                if (head_0.data >= head_i.data) {
                    arr[i] = head_i.next;
                    head_i.next = head_0;
                    arr[0] = head_i;
                }
                else {
 
                    // Traverse the first list
                    while (head_0.next != null) {
 
                        // Smaller than next element
                        if (head_0.next.data
                            >= head_i.data) {
                            arr[i] = head_i.next;
                            head_i.next = head_0.next;
                            head_0.next = head_i;
                            break;
                        }
 
                        // go to next node
                        head_0 = head_0.next;
 
                        // if last node
                        if (head_0.next == null) {
                            arr[i] = head_i.next;
                            head_i.next = null;
                            head_0.next = head_i;
                            head_0.next.next = null;
                            break;
                        }
                    }
                }
            }
        }
        return arr[0];
    }
    static public void Main()
    {
 
        // Number of linked lists
        int k = 3;
 
        // an array of pointers storing the
        // head nodes of the linked lists
        Node[] arr = new Node[k];
 
        arr[0] = new Node(1);
        arr[0].next = new Node(3);
        arr[0].next.next = new Node(5);
        arr[0].next.next.next = new Node(7);
 
        arr[1] = new Node(2);
        arr[1].next = new Node(4);
        arr[1].next.next = new Node(6);
        arr[1].next.next.next = new Node(8);
 
        arr[2] = new Node(0);
        arr[2].next = new Node(9);
        arr[2].next.next = new Node(10);
        arr[2].next.next.next = new Node(11);
 
        // Merge all lists
        head = mergeKLists(arr, k - 1);
        printList(head);
    }
}
 

Javascript

<script>
// Javascript program to merge k sorted
// arrays of size n each
     
    // A Linked List node
    class Node
    {
        // Utility function to create a new node.
        constructor(key)
        {
            this.data=key;
            this.next=null;
        }
    }
     
    let head;
    let temp;
 
/* Function to print nodes in
a given linked list */
function printList(node)
{
    while(node != null)
    {
      document.write(node.data + " ");
  
      node = node.next;
    }
    document.write("<br>");
         
}
 
// The main function that
// takes an array of lists
// arr[0..last] and generates
// the sorted output
function mergeKLists(arr,last)
{
    // Traverse form second list to last
    for (let i = 1; i <= last; i++)
    {
      while(true)
      {
  
        // head of both the lists,
        // 0 and ith list. 
        let head_0 = arr[0];
        let head_i = arr[i];
  
        // Break if list ended
        if (head_i == null)
          break;
  
        // Smaller than first element
        if(head_0.data >= head_i.data)
        {
          arr[i] = head_i.next;
          head_i.next = head_0;
          arr[0] = head_i;
        }
        else
        {
  
          // Traverse the first list
          while (head_0.next != null)
          {
  
            // Smaller than next element
            if (head_0.next.data >= head_i.data)
            {
              arr[i] = head_i.next;
              head_i.next = head_0.next;
              head_0.next = head_i;
              break;
            }
  
            // go to next node
            head_0 = head_0.next;
  
            // if last node
            if (head_0.next == null)
            {
              arr[i] = head_i.next;
              head_i.next = null;
              head_0.next = head_i;
              head_0.next.next = null;
              break;
            }
          }
        }
      }
    }
    return arr[0];
}
 
// Driver program to test
// above functions 
// Number of linked lists
let k = 3;
// Number of elements in each list
let n = 4;
// an array of pointers storing the
// head nodes of the linked lists
let  arr = new Array(k);
arr[0] = new Node(1);
arr[0].next = new Node(3);
arr[0].next.next = new Node(5);
arr[0].next.next.next = new Node(7);
 
arr[1] = new Node(2);
arr[1].next = new Node(4);
arr[1].next.next = new Node(6);
arr[1].next.next.next = new Node(8);
 
arr[2] = new Node(0);
arr[2].next = new Node(9);
arr[2].next.next = new Node(10);
arr[2].next.next.next = new Node(11);
 
// Merge all lists
head = mergeKLists(arr, k - 1);
printList(head);
 
     
 
 
</script>

输出

0 1 2 3 4 5 6 7 8 9 10 11 

时间复杂度:O(N^(K-1)),在K-1个列表上遍历N次。 辅助空间:O(1)。

分而治之合并 K 个排序链表:

两两配对合并,然后将剩下的 K/2 个列表再进行两两合并,重复此操作,直到所有列表都合并。

请按照以下步骤解决问题:

  • 将 K 个列表配对并合并。
  • 第一次循环后,剩下 K/2 个列表,每个列表的大小为 2N。第二次循环后,剩下 K/4 个列表,每个列表的大小为 4N,依此类推。
  • 重复该过程,直到只剩下一个列表。

下面是上述想法的实现。

C++

// C++ program to merge k sorted
// arrays of size n each
#include <bits/stdc++.h>
using namespace std;
 
// A Linked List node
struct Node {
    int data;
    Node* next;
};
 
/* Function to print nodes in
   a given linked list */
void printList(Node* node)
{
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
}
 
/* Takes two lists sorted in increasing order, and merge
   their nodes together to make one big sorted list. Below
   function takes O(n) extra space for recursive calls,
    */
Node* SortedMerge(Node* a, Node* b)
{
    Node* result = NULL;
 
    /* Base cases */
    if (a == NULL)
        return (b);
    else if (b == NULL)
        return (a);
 
    /* Pick either a or b, and recur */
    if (a->data <= b->data) {
        result = a;
        result->next = SortedMerge(a->next, b);
    }
    else {
        result = b;
        result->next = SortedMerge(a, b->next);
    }
 
    return result;
}
 
// The main function that takes an array of lists
// arr[0..last] and generates the sorted output
Node* mergeKLists(Node* arr[], int last)
{
    // repeat until only one list is left
    while (last != 0) {
        int i = 0, j = last;
 
        // (i, j) forms a pair
        while (i < j) {
            // merge List i with List j and store
            // merged list in List i
            arr[i] = SortedMerge(arr[i], arr[j]);
 
            // consider next pair
            i++, j--;
 
            // If all pairs are merged, update last
            if (i >= j)
                last = j;
        }
    }
 
    return arr[0];
}
 
// Utility function to create a new node.
Node* newNode(int data)
{
    struct Node* temp = new Node;
    temp->data = data;
    temp->next = NULL;
    return temp;
}
 
// Driver program to test above functions
int main()
{
    int k = 3; // Number of linked lists
    int n = 4; // Number of elements in each list
 
    // an array of pointers storing the head nodes
    // of the linked lists
    Node* arr[k];
 
    arr[0] = newNode(1);
    arr[0]->next = newNode(3);
    arr[0]->next->next = newNode(5);
    arr[0]->next->next->next = newNode(7);
 
    arr[1] = newNode(2);
    arr[1]->next = newNode(4);
    arr[1]->next->next = newNode(6);
    arr[1]->next->next->next = newNode(8);
 
    arr[2] = newNode(0);
    arr[2]->next = newNode(9);
    arr[2]->next->next = newNode(10);
    arr[2]->next->next->next = newNode(11);
 
    // Merge all lists
    Node* head = mergeKLists(arr, k - 1);
 
    printList(head);
 
    return 0;
}

Java

// Java program to merge k sorted arrays of size n each
public class MergeKSortedLists {
 
    /* Takes two lists sorted in increasing order, and merge
    their nodes together to make one big sorted list. Below
    function takes O(Log n) extra space for recursive calls,
    but it can be easily modified to work with same time and
    O(1) extra space  */
    public static Node SortedMerge(Node a, Node b)
    {
        Node result = null;
        /* Base cases */
        if (a == null)
            return b;
        else if (b == null)
            return a;
 
        /* Pick either a or b, and recur */
        if (a.data <= b.data) {
            result = a;
            result.next = SortedMerge(a.next, b);
        }
        else {
            result = b;
            result.next = SortedMerge(a, b.next);
        }
 
        return result;
    }
 
    // The main function that takes an array of lists
    // arr[0..last] and generates the sorted output
    public static Node mergeKLists(Node arr[], int last)
    {
        // repeat until only one list is left
        while (last != 0) {
            int i = 0, j = last;
 
            // (i, j) forms a pair
            while (i < j) {
                // merge List i with List j and store
                // merged list in List i
                arr[i] = SortedMerge(arr[i], arr[j]);
 
                // consider next pair
                i++;
                j--;
 
                // If all pairs are merged, update last
                if (i >= j)
                    last = j;
            }
        }
 
        return arr[0];
    }
 
    /* Function to print nodes in a given linked list */
    public static void printList(Node node)
    {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }
 
    public static void main(String args[])
    {
        int k = 3; // Number of linked lists
        int n = 4; // Number of elements in each list
 
        // an array of pointers storing the head nodes
        // of the linked lists
        Node arr[] = new Node[k];
 
        arr[0] = new Node(1);
        arr[0].next = new Node(3);
        arr[0].next.next = new Node(5);
        arr[0].next.next.next = new Node(7);
 
        arr[1] = new Node(2);
        arr[1].next = new Node(4);
        arr[1].next.next = new Node(6);
        arr[1].next.next.next = new Node(8);
 
        arr[2] = new Node(0);
        arr[2].next = new Node(9);
        arr[2].next.next = new Node(10);
        arr[2].next.next.next = new Node(11);
 
        // Merge all lists
        Node head = mergeKLists(arr, k - 1);
        printList(head);
    }
}
 
class Node {
    int data;
    Node next;
    Node(int data) { this.data = data; }
}

Python

# Python3 program to merge k sorted
# arrays of size n each
 
# A Linked List node
class Node:
 
    def __init__(self):
 
        self.data = 0
        self.next = None
 
# Function to print nodes in a
# given linked list
def printList(node):
 
    while (node != None):
        print(node.data, end=' ')
        node = node.next
 
# Takes two lists sorted in increasing order,
# and merge their nodes together to make one
# big sorted list. Below function takes
# O(Log n) extra space for recursive calls,
# but it can be easily modified to work with
# same time and O(1) extra space
def SortedMerge(a, b):
 
    result = None
 
    # Base cases
    if (a == None):
        return(b)
    elif (b == None):
        return(a)
 
    # Pick either a or b, and recur
    if (a.data <= b.data):
        result = a
        result.next = SortedMerge(a.next, b)
    else:
        result = b
        result.next = SortedMerge(a, b.next)
 
    return result
 
# The main function that takes an array of lists
# arr[0..last] and generates the sorted output
def mergeKLists(arr, last):
 
    # Repeat until only one list is left
    while (last != 0):
        i = 0
        j = last
 
        # (i, j) forms a pair
        while (i < j):
 
            # Merge List i with List j and store
            # merged list in List i
            arr[i] = SortedMerge(arr[i], arr[j])
 
            # Consider next pair
            i += 1
            j -= 1
 
            # If all pairs are merged, update last
            if (i >= j):
                last = j
 
    return arr[0]
 
# Utility function to create a new node.
def newNode(data):
 
    temp = Node()
    temp.data = data
    temp.next = None
    return temp
 
 
# Driver code
if __name__ == '__main__':
 
    # Number of linked lists
    k = 3
 
    # Number of elements in each list
    n = 4
 
    # An array of pointers storing the
    # head nodes of the linked lists
    arr = [0 for i in range(k)]
 
    arr[0] = newNode(1)
    arr[0].next = newNode(3)
    arr[0].next.next = newNode(5)
    arr[0].next.next.next = newNode(7)
 
    arr[1] = newNode(2)
    arr[1].next = newNode(4)
    arr[1].next.next = newNode(6)
    arr[1].next.next.next = newNode(8)
 
    arr[2] = newNode(0)
    arr[2].next = newNode(9)
    arr[2].next.next = newNode(10)
    arr[2].next.next.next = newNode(11)
 
    # Merge all lists
    head = mergeKLists(arr, k - 1)
 
    printList(head)
 

C#

// C# program to merge k sorted arrays of size n each
using System;
 
public class MergeKSortedLists {
 
    /* Takes two lists sorted in
    increasing order, and merge
    their nodes together to make
    one big sorted list. Below
    function takes O(Log n) extra
    space for recursive calls,
    but it can be easily modified
    to work with same time and
    O(1) extra space */
    public static Node SortedMerge(Node a, Node b)
    {
        Node result = null;
 
        /* Base cases */
        if (a == null)
            return b;
        else if (b == null)
            return a;
 
        /* Pick either a or b, and recur */
        if (a.data <= b.data) {
            result = a;
            result.next = SortedMerge(a.next, b);
        }
        else {
            result = b;
            result.next = SortedMerge(a, b.next);
        }
 
        return result;
    }
 
    // The main function that takes
    // an array of lists arr[0..last]
    // and generates the sorted output
    public static Node mergeKLists(Node[] arr, int last)
    {
        // repeat until only one list is left
        while (last != 0) {
            int i = 0, j = last;
 
            // (i, j) forms a pair
            while (i < j) {
                // merge List i with List j and store
                // merged list in List i
                arr[i] = SortedMerge(arr[i], arr[j]);
 
                // consider next pair
                i++;
                j--;
 
                // If all pairs are merged, update last
                if (i >= j)
                    last = j;
            }
        }
 
        return arr[0];
    }
 
    /* Function to print nodes in a given linked list */
    public static void printList(Node node)
    {
        while (node != null) {
            Console.Write(node.data + " ");
            node = node.next;
        }
    }
 
    public static void Main()
    {
        int k = 3; // Number of linked lists
        // int n = 4; // Number of elements in each list
 
        // An array of pointers storing the head nodes
        // of the linked lists
        Node[] arr = new Node[k];
 
        arr[0] = new Node(1);
        arr[0].next = new Node(3);
        arr[0].next.next = new Node(5);
        arr[0].next.next.next = new Node(7);
 
        arr[1] = new Node(2);
        arr[1].next = new Node(4);
        arr[1].next.next = new Node(6);
        arr[1].next.next.next = new Node(8);
 
        arr[2] = new Node(0);
        arr[2].next = new Node(9);
        arr[2].next.next = new Node(10);
        arr[2].next.next.next = new Node(11);
 
        // Merge all lists
        Node head = mergeKLists(arr, k - 1);
        printList(head);
    }
}
 
public class Node {
    public int data;
    public Node next;
    public Node(int data) { this.data = data; }
}
 

Javascript

<script>
 
// JavaScript program to merge k sorted
// arrays of size n each
class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}
 
    /*
      Takes two lists sorted in increasing order, 
     and merge their nodes together to
     make one big sorted list. 
     Below function takes O(Log n) extra space for
     * recursive calls, but it can be easily modified
     to work with same time and
     * O(1) extra space
     */
    function SortedMerge(a,  b) {
var result = null;
        /* Base cases */
        if (a == null)
            return b;
        else if (b == null)
            return a;
 
        /* Pick either a or b, and recur */
        if (a.data <= b.data) {
            result = a;
            result.next = SortedMerge(a.next, b);
        } else {
            result = b;
            result.next = SortedMerge(a, b.next);
        }
 
        return result;
    }
 
    // The main function that takes an array of lists
    // arr[0..last] and generates the sorted output
    function mergeKLists(arr , last) {
        // repeat until only one list is left
        while (last != 0) {
            var i = 0, j = last;
 
            // (i, j) forms a pair
            while (i < j) {
                // merge List i with List j and store
                // merged list in List i
                arr[i] = SortedMerge(arr[i], arr[j]);
 
                // consider next pair
                i++;
                j--;
 
                // If all pairs are merged, update last
                if (i >= j)
                    last = j;
            }
        }
 
        return arr[0];
    }
 
    /* Function to print nodes in a given linked list */
    function printList(node) {
        while (node != null) {
            document.write(node.data + " ");
            node = node.next;
        }
    }
 
     
        var k = 3; // Number of linked lists
        var n = 4; // Number of elements in each list
 
        // an array of pointers storing the head nodes
        // of the linked lists
var arr = Array(k);
 
        arr[0] = new Node(1);
        arr[0].next = new Node(3);
        arr[0].next.next = new Node(5);
        arr[0].next.next.next = new Node(7);
 
        arr[1] = new Node(2);
        arr[1].next = new Node(4);
        arr[1].next.next = new Node(6);
        arr[1].next.next.next = new Node(8);
 
        arr[2] = new Node(0);
        arr[2].next = new Node(9);
        arr[2].next.next = new Node(10);
        arr[2].next.next.next = new Node(11);
 
        // Merge all lists
var head = mergeKLists(arr, k - 1);
        printList(head);
 
 
</script>

输出

0 1 2 3 4 5 6 7 8 9 10 11 

时间复杂度:O(N * K * log K)
空间复杂度:O(N * K)

通过选择顶部元素的最小值来合并 K 个排序链表:

选择顶部元素的最小值,将其存储在结果链表中,并递增最小元素的指针。

请按照以下步骤解决问题:

  • 初始化 K 个指针, 指向每个列表的第一个元素
  • 找到K个列表中值最小的节点并将指针后移,指向下一个节点。
  • 将该最小值节点加到结果列表的头指针后面,并将头指针后移一位
  • 重复这些步骤,直到所有节点都被使用。

下面是上述方法的实现:

C++

// C++ program to merge k sorted arrays of size n each
#include <bits/stdc++.h>
using namespace std;
 
// A Linked List node
struct Node {
    int data;
    Node* next;
    Node(int x)
    {
        data = x;
        next = NULL;
    }
};
 
/* Function to print nodes in a given linked list */
void printList(Node* node)
{
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
    cout << endl;
}
 
/*Linked list Node structure
 
struct Node
{
int data;
Node* next;
Node(int x){
    data = x;
    next = NULL;
}
};
*/
 
    // Function to merge K sorted linked list.
    Node* mergeKLists(Node* arr[], int K)
    {
        Node* head = NULL;
        while (1) {
            int a = 0;
            int z;
            Node* curr;
            int min = INT_MAX;
            for (int i = 0; i < K; i++) {
                if (arr[i] != NULL) {
                    a++;
                    if (arr[i]->data < min) {
                        min = arr[i]->data;
                        z = i;
                    }
                }
            }
            if (a != 0) {
                arr[z] = arr[z]->next;
                Node* temp = new Node(min);
                if (head == NULL) {
                    head = temp;
                    curr = temp;
                }
                else {
                    curr->next = temp;
                    curr = temp;
                }
            }
            else {
                return head;
            }
        }
    }
 
// { Driver Code Starts.
 
// Driver program to test above functions
int main()
{
    int k = 3; // Number of linked lists
    int n = 4; // Number of elements in each list
 
    // an array of pointers storing the head nodes
    // of the linked lists
    Node* arr[k];
 
    arr[0] = new Node(1);
    arr[0]->next = new Node(3);
    arr[0]->next->next = new Node(5);
    arr[0]->next->next->next = new Node(7);
 
    arr[1] = new Node(2);
    arr[1]->next = new Node(4);
    arr[1]->next->next = new Node(6);
    arr[1]->next->next->next = new Node(8);
 
    arr[2] = new Node(0);
    arr[2]->next = new Node(9);
    arr[2]->next->next = new Node(10);
    arr[2]->next->next->next = new Node(11);
     
    Node* head = mergeKLists(arr, k);
 
    printList(head);
    return 0;
}
 
// } Driver Code Ends

Java

// Java program to merge k sorted arrays of size n each
import java.util.*;
 
// A Linked List node
class Node {
    int data;
    Node next;
    Node(int x) {
        data = x;
        next = null;
    }
}
 
public class MergeKSortedLists {
 
    /* Function to print nodes in a given linked list */
    static void printList(Node node) {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
        System.out.println();
    }
 
    // Function to merge K sorted linked lists.
    static Node mergeKLists(Node[] arr, int K) {
        Node head = null;
        Node curr = null; // Initialize curr
 
        while (true) {
            int a = 0;
            int z = 0;
            int min = Integer.MAX_VALUE;
 
            for (int i = 0; i < K; i++) {
                if (arr[i] != null) {
                    a++;
                    if (arr[i].data < min) {
                        min = arr[i].data;
                        z = i;
                    }
                }
            }
            if (a != 0) {
                arr[z] = arr[z].next;
                Node temp = new Node(min);
                if (head == null) {
                    head = temp;
                    curr = temp;
                } else {
                    curr.next = temp;
                    curr = temp;
                }
            } else {
                return head;
            }
        }
    }
 
    // Driver program to test above functions
    public static void main(String[] args) {
        int k = 3; // Number of linked lists
        int n = 4; // Number of elements in each list
 
        // an array of pointers storing the head nodes
        // of the linked lists
        Node[] arr = new Node[k];
 
        arr[0] = new Node(1);
        arr[0].next = new Node(3);
        arr[0].next.next = new Node(5);
        arr[0].next.next.next = new Node(7);
 
        arr[1] = new Node(2);
        arr[1].next = new Node(4);
        arr[1].next.next = new Node(6);
        arr[1].next.next.next = new Node(8);
 
        arr[2] = new Node(0);
        arr[2].next = new Node(9);
        arr[2].next.next = new Node(10);
        arr[2].next.next.next = new Node(11);
 
        Node head = mergeKLists(arr, k);
 
        printList(head);
    }
}
 

Python

# Python program to merge k sorted arrays of size n each
 
# A Linked List node
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None
 
# Function to merge K sorted linked lists
def mergeKLists(arr, K):
    from queue import PriorityQueue
 
    # Create a priority queue
    pq = PriorityQueue()
 
    # Push the first elements of all linked lists into the priority queue
    for i in range(K):
        if arr[i] is not None:
            pq.put((arr[i].data, i))
 
    head = Node(None)
    curr = head
 
    # Merge the linked lists
    while not pq.empty():
        val, i = pq.get()
        curr.next = Node(val)
        curr = curr.next
        if arr[i].next is not None:
            pq.put((arr[i].next.data, i))
            arr[i] = arr[i].next
 
    return head.next
 
# Function to print nodes in a given linked list
def printList(node):
    while node is not None:
        print(node.data, end=' ')
        node = node.next
    print()
 
# Driver program to test the functions
if __name__ == '__main__':
    k = 3  # Number of linked lists
    n = 4  # Number of elements in each list
 
    # An array of pointers storing the head nodes
    # of the linked lists
    arr = [None] * k
 
    arr[0] = Node(1)
    arr[0].next = Node(3)
    arr[0].next.next = Node(5)
    arr[0].next.next.next = Node(7)
 
    arr[1] = Node(2)
    arr[1].next = Node(4)
    arr[1].next.next = Node(6)
    arr[1].next.next.next = Node(8)
 
    arr[2] = Node(0)
    arr[2].next = Node(9)
    arr[2].next.next = Node(10)
    arr[2].next.next.next = Node(11)
 
    head = mergeKLists(arr, k)
 
    print("Merged Linked List:")
    printList(head)
 

C#

using System;
 
// A Linked List node
public class Node {
    public int data;
    public Node next;
    public Node(int x)
    {
        data = x;
        next = null;
    }
}
 
class GFG {
    // Function to print nodes in a given linked list
    static void PrintList(Node node)
    {
        while (node != null) {
            Console.Write(node.data + " ");
            node = node.next;
        }
        Console.WriteLine();
    }
 
    // Function to merge K sorted linked lists
    static Node MergeKLists(Node[] arr, int K)
    {
        Node head = null;
        Node curr = null; // Initialize curr
        while (true) {
            int a = 0;
            int z = 0; // Initialize z
            int min = int.MaxValue;
            for (int i = 0; i < K; i++) {
                if (arr[i] != null) {
                    a++;
                    if (arr[i].data < min) {
                        min = arr[i].data;
                        z = i;
                    }
                }
            }
            if (a != 0) {
                arr[z] = arr[z].next;
                Node temp = new Node(min);
                if (head == null) {
                    head = temp;
                    curr = temp;
                }
                else {
                    curr.next = temp;
                    curr = temp;
                }
            }
            else {
                return head;
            }
        }
    }
 
    // Driver program to test above functions
    public static void Main(string[] args)
    {
        int k = 3; // Number of linked lists
 
        // an array of pointers storing the head nodes
        // of the linked lists
        Node[] arr = new Node[k];
 
        arr[0] = new Node(1);
        arr[0].next = new Node(3);
        arr[0].next.next = new Node(5);
        arr[0].next.next.next = new Node(7);
 
        arr[1] = new Node(2);
        arr[1].next = new Node(4);
        arr[1].next.next = new Node(6);
        arr[1].next.next.next = new Node(8);
 
        arr[2] = new Node(0);
        arr[2].next = new Node(9);
        arr[2].next.next = new Node(10);
        arr[2].next.next.next = new Node(11);
 
        Node head = MergeKLists(arr, k);
 
        PrintList(head);
    }
}

Javascript

// Definition for singly-linked list.
class ListNode {
    constructor(val) {
        this.val = val;
        this.next = null;
    }
}
 
/**
 * Function to merge K sorted linked lists.
 * @param {ListNode[]} lists - An array of linked list nodes.
 * @return {ListNode} - The merged linked list.
 */
const mergeKLists = (lists) => {
    const mergeTwoLists = (l1, l2) => {
        if (!l1) return l2;
        if (!l2) return l1;
 
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    };
 
    const mergeKListsRecursively = (lists, start, end) => {
        if (start === end) {
            return lists[start];
        }
        const mid = Math.floor((start + end) / 2);
        const left = mergeKListsRecursively(lists, start, mid);
        const right = mergeKListsRecursively(lists, mid + 1, end);
        return mergeTwoLists(left, right);
    };
 
    if (lists.length === 0) return null;
    return mergeKListsRecursively(lists, 0, lists.length - 1);
};
 
// Driver program to test above functions
const k = 3; // Number of linked lists
 
// An array of linked list nodes storing the head nodes of the linked lists
const arr = [];
 
arr[0] = new ListNode(1);
arr[0].next = new ListNode(3);
arr[0].next.next = new ListNode(5);
arr[0].next.next.next = new ListNode(7);
 
arr[1] = new ListNode(2);
arr[1].next = new ListNode(4);
arr[1].next.next = new ListNode(6);
arr[1].next.next.next = new ListNode(8);
 
arr[2] = new ListNode(0);
arr[2].next = new ListNode(9);
arr[2].next.next = new ListNode(10);
arr[2].next.next.next = new ListNode(11);
 
const head = mergeKLists(arr);
 
// Function to print nodes in a given linked list
const printList = (node) => {
    while (node !== null) {
        process.stdout.write(`${node.val} `);
        node = node.next;
    }
    console.log();
};
 
printList(head);

输出

0 1 2 3 4 5 6 7 8 9 10 11 

时间复杂度:O(N*(K^2))
辅助空间:O(K)

未完待续-最小堆
书接下回 合并 k 个排序链表 (2)