📜  合并两个未排序的链表得到一个排序的列表 – Set 2

📅  最后修改于: 2022-05-13 01:56:10.614000             🧑  作者: Mango

合并两个未排序的链表得到一个排序的列表 – Set 2

给定两个未排序的链表N个节点的L1M个节点的L2 ,任务是将它们合并以得到一个排序的单链表

例子:

注意:在 O(1) 辅助空间中解决此问题的内存高效方法已在此处接近,

方法:这个想法是使用一个辅助数组来存储两个链表的元素,然后按升序对数组进行排序。最后,将所有元素重新插入到链表中。请按照以下步骤解决问题:

  • 通过将第一个列表的尾节点L1的下一个指向第二个列表的第一个节点L2来连接两个列表。
  • 遍历链表L1 ,并将所有元素推入向量V
  • 按升序对向量 V 进行排序。
  • 排序后,将所有元素插入到列表L1中。

以下是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Linked list node
class Node {
public:
    int data;
    Node* next;
};
 
// Utility function to append key at
// end of linked list
void insertNode(Node** head, int x)
{
    Node* ptr = new Node;
    ptr->data = x;
    ptr->next = NULL;
    if (*head == NULL) {
        *head = ptr;
    }
    else {
        Node* temp;
        temp = *head;
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = ptr;
    }
}
 
// Utility function to print linkedlist
void display(Node** head)
{
    Node* temp;
    temp = *head;
    if (temp == NULL) {
        cout << "NULL \n";
    }
    else {
        while (temp != NULL) {
            cout << temp->data;
            if (temp->next != NULL)
                cout << "->";
            temp = temp->next;
        }
    }
}
 
// Function to merge two linked lists
void MergeLinkedlist(Node** head1, Node** head2)
{
    Node* ptr;
    ptr = *head1;
    while (ptr->next != NULL) {
        ptr = ptr->next;
    }
 
    // Join linked list by placing address of
    // first node of L2 in the last node of L1
    ptr->next = *head2;
}
 
// Function to merge two unsorted linked
// lists to get a sorted list
void sortLinkedList(Node** head, Node** head1)
{
    // Function call to merge the two lists
    MergeLinkedlist(head, head1);
 
    // Declare a vector
    vector V;
    Node* ptr = *head;
 
    // Push all elements into vector
    while (ptr != NULL) {
        V.push_back(ptr->data);
        ptr = ptr->next;
    }
 
    // Sort the vector
    sort(V.begin(), V.end());
    int index = 0;
    ptr = *head;
 
    // Insert elements in the linked
    // list from the vector
    while (ptr != NULL) {
        ptr->data = V[index];
        index++;
        ptr = ptr->next;
    }
 
    // Display the sorted and
    // merged linked list
    display(head);
}
 
// Driver Code
int main()
{
    // Given linked list, L1
    Node* head1 = NULL;
    insertNode(&head1, 3);
    insertNode(&head1, 5);
    insertNode(&head1, 1);
 
    // Given linked list, L2
    Node* head2 = NULL;
    insertNode(&head2, 6);
    insertNode(&head2, 2);
    insertNode(&head2, 4);
    insertNode(&head2, 9);
 
    // Function Call
    sortLinkedList(&head1, &head2);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Linked list node
    static class Node {
        int data;
        Node next;
    };
    static Node head1, head2;
   
    // Utility function to append key at
    // end of linked list
    static Node insertNode(Node head, int x)
    {
        Node ptr = new Node();
        ptr.data = x;
        ptr.next = null;
        if (head == null) {
            head = ptr;
        }
        else {
            Node temp;
            temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = ptr;
        }
 
        return head;
    }
 
    // Utility function to print linkedlist
    static void display(Node head)
    {
        Node temp;
        temp = head;
        if (temp == null) {
            System.out.print("null \n");
        }
        else {
            while (temp != null) {
                System.out.print(temp.data);
                if (temp.next != null)
                    System.out.print("->");
                temp = temp.next;
            }
        }
    }
 
    // Function to merge two linked lists
    static Node MergeLinkedlist()
    {
        Node ptr;
        ptr = head1;
        while (ptr.next != null) {
            ptr = ptr.next;
        }
 
        // Join linked list by placing address of
        // first node of L2 in the last node of L1
        ptr.next = head2;
 
        return head1;
    }
 
    // Function to merge two unsorted linked
    // lists to get a sorted list
    static void sortLinkedList()
    {
        // Function call to merge the two lists
        Node head = MergeLinkedlist();
 
        // Declare a vector
        Vector V = new Vector<>();
        Node ptr = head;
 
        // Push all elements into vector
        while (ptr != null) {
            V.add(ptr.data);
            ptr = ptr.next;
        }
        Collections.sort(V);
        // Sort the vector
        ;
        int index = 0;
        ptr = head;
 
        // Insert elements in the linked
        // list from the vector
        while (ptr != null) {
            ptr.data = V.get(index);
            index++;
            ptr = ptr.next;
        }
 
        // Display the sorted and
        // merged linked list
        display(head);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given linked list, L1
 
        head1 = insertNode(head1, 3);
        head1 = insertNode(head1, 5);
        head1 = insertNode(head1, 1);
 
        // Given linked list, L2
        head2 = null;
        head2 = insertNode(head2, 6);
        head2 = insertNode(head2, 2);
        head2 = insertNode(head2, 4);
        head2 = insertNode(head2, 9);
 
        // Function Call
        sortLinkedList();
    }
}
 
// This code is contributed by umadevi9616


Python3
# Py program for the above approach
 
# Linked list node
class Node:
    def __init__(self, d):
        self.data = d
        self.next = None
 
# Utility function to append key at
# end of linked list
def insertNode(head, x):
    ptr = Node(x)
    if (head == None):
        head = ptr
    else:
        temp = head
        while (temp.next != None):
            temp = temp.next
        temp.next = ptr
    return head
 
# Utility function to print linkedlist
def display(head):
    temp = head
    if (temp == None):
        print ("None")
    else:
        while (temp.next != None):
            print (temp.data,end="->")
            if (temp.next != None):
                print ("",end="")
            temp = temp.next
        print(temp.data)
 
# Function to merge two linked lists
def MergeLinkedlist(head1, head2):
    ptr = head1
    while (ptr.next != None):
        ptr = ptr.next
 
    # Join linked list by placing address of
    # first node of L2 in the last node of L1
    ptr.next = head2
 
    return head1
 
# Function to merge two unsorted linked
# lists to get a sorted list
def sortLinkedList(head1, head2):
    # Function call to merge the two lists
    head1 = MergeLinkedlist(head1, head2)
 
    # Declare a vector
    V = []
    ptr = head1
 
    # Push all elements into vector
    while (ptr != None):
        V.append(ptr.data)
        ptr = ptr.next
 
    # Sort the vector
    V = sorted(V)
    index = 0
    ptr = head1
 
    # Insert elements in the linked
    # list from the vector
    while (ptr != None):
        ptr.data = V[index]
        index += 1
        ptr = ptr.next
 
    # Display the sorted and
    # merged linked list
    display(head1)
 
# Driver Code
if __name__ == '__main__':
    # Given linked list, L1
    head1 = None
    head1 = insertNode(head1, 3)
    head1 = insertNode(head1, 5)
    head1 = insertNode(head1, 1)
 
 
    # Given linked list, L2
    head2 = None
    head2 = insertNode(head2, 6)
    head2 = insertNode(head2, 2)
    head2 = insertNode(head2, 4)
    head2 = insertNode(head2, 9)
 
    # Function Call
    sortLinkedList(head1, head2)
 
# This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Linked list node
public    class Node {
    public    int data;
    public    Node next;
    };
 
    static Node head1, head2;
 
    // Utility function to append key at
    // end of linked list
    static Node insertNode(Node head, int x) {
        Node ptr = new Node();
        ptr.data = x;
        ptr.next = null;
        if (head == null) {
            head = ptr;
        } else {
            Node temp;
            temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = ptr;
        }
 
        return head;
    }
 
    // Utility function to print linkedlist
    static void display(Node head) {
        Node temp;
        temp = head;
        if (temp == null) {
            Console.Write("null \n");
        } else {
            while (temp != null) {
                Console.Write(temp.data);
                if (temp.next != null)
                    Console.Write("->");
                temp = temp.next;
            }
        }
    }
 
    // Function to merge two linked lists
    static Node MergeLinkedlist() {
        Node ptr;
        ptr = head1;
        while (ptr.next != null) {
            ptr = ptr.next;
        }
 
        // Join linked list by placing address of
        // first node of L2 in the last node of L1
        ptr.next = head2;
 
        return head1;
    }
 
    // Function to merge two unsorted linked
    // lists to get a sorted list
    static void sortList()
    {
       
        // Function call to merge the two lists
        Node head = MergeLinkedlist();
 
        // Declare a vector
        List V = new List();
        Node ptr = head;
 
        // Push all elements into vector
        while (ptr != null) {
            V.Add(ptr.data);
            ptr = ptr.next;
        }
        V.Sort();
        // Sort the vector
        ;
        int index = 0;
        ptr = head;
 
        // Insert elements in the linked
        // list from the vector
        while (ptr != null) {
            ptr.data = V[index];
            index++;
            ptr = ptr.next;
        }
 
        // Display the sorted and
        // merged linked list
        display(head);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
       
        // Given linked list, L1
 
        head1 = insertNode(head1, 3);
        head1 = insertNode(head1, 5);
        head1 = insertNode(head1, 1);
 
        // Given linked list, L2
        head2 = null;
        head2 = insertNode(head2, 6);
        head2 = insertNode(head2, 2);
        head2 = insertNode(head2, 4);
        head2 = insertNode(head2, 9);
 
        // Function Call
        sortList();
    }
}
 
// This code is contributed by umadevi9616


Javascript
// Javascript program for the above approach
 
// Linked list node
class Node {
    constructor(d) {
        this.data = d
        this.next = null
    }
}
 
// Utility function to append key at
// end of linked list
function insertNode(head, x) {
    ptr = new Node(x)
    if (head == null) {
        head = ptr
    } else {
        temp = head
        while (temp.next != null) {
            temp = temp.next
        }
        temp.next = ptr
    }
    return head
}
 
// Utility function to print linkedlist
function display(head) {
    let temp = head
    if (temp == null) {
        document.write("null")
    }
    else {
        while (temp.next != null) {
            document.write(temp.data, end = "->")
            if (temp.next != null)
                document.write("", end = "")
            temp = temp.next
        }
        document.write(temp.data)
    }
}
 
// Function to merge two linked lists
function MergeLinkedlist(head1, head2) {
    let ptr = head1
    while (ptr.next != null)
        ptr = ptr.next
 
    // Join linked list by placing address of
    // first node of L2 in the last node of L1
    ptr.next = head2
 
    return head1
}
 
// Function to merge two unsorted linked
// lists to get a sorted list
function sortLinkedList(head1, head2) {
    // Function call to merge the two lists
    head1 = MergeLinkedlist(head1, head2)
 
    // Declare a vector
    let V = []
    let ptr = head1
 
    // Push all elements into vector
    while (ptr != null) {
        V.push(ptr.data)
        ptr = ptr.next
    }
 
    // Sort the vector
    V = V.sort((a, b) => a - b)
    index = 0
    ptr = head1
 
    // Insert elements in the linked
    // list from the vector
    while (ptr != null) {
        ptr.data = V[index]
        index += 1
        ptr = ptr.next
    }
 
    // Display the sorted and
    // merged linked list
    display(head1)
}
 
// Driver Code
 
// Given linked list, L1
let head1 = null;
head1 = insertNode(head1, 3)
head1 = insertNode(head1, 5)
head1 = insertNode(head1, 1)
 
 
// Given linked list, L2
let head2 = null
head2 = insertNode(head2, 6)
head2 = insertNode(head2, 2)
head2 = insertNode(head2, 4)
head2 = insertNode(head2, 9)
 
// Function Call
sortLinkedList(head1, head2)
 
// This code is contributed by gfgking


输出
1->2->3->4->5->6->9

时间复杂度: O((N+M)*log(N+M))
辅助空间: O(N+M)