c_cpp 合并两个已排序的链接列表

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 合并两个已排序的链接列表相关的知识,希望对你有一定的参考价值。

// https://www.geeksforgeeks.org/merge-two-sorted-linked-lists/
#include <iostream>
#include <list>
using namespace std;

struct linked_list {
    int data;
    struct linked_list *next;
};
typedef struct linked_list node;

void print (node* n) {
    while(n) {
        cout<< n->data<< "->";
        n = n->next;
    }
    cout<< "NULL";
}

void insert(node **headref, int n) {
    node *last = *headref;
    node* temp = new node;
    temp->data = n;
    temp->next = NULL;
    if (last == NULL) {
        *headref = temp;
        return;
    }
    while (last->next)
        last = last->next;
    last->next = temp;
    return;
}

node* merge(node* head1, node* head2) {
    node *temp = new node;
    node *temp1 = head1, *temp2=head2, *head = NULL;
    while (temp1 && temp2) {
        if (temp1->data < temp2->data) {
            insert(&head, temp1->data);
            temp1 = temp1->next;
        }
        else {
            insert(&head, temp2->data);
            temp2 = temp2->next;
        }
    }
    while (temp1) {
        insert(&head, temp1->data);
        temp1 = temp1->next;
    }
    while (temp2) {
        insert(&head, temp2->data);
        temp2 = temp2->next;
    }
    return head;
}

int main() {
    int n;
    node* head1=NULL, *head2 = NULL;

    cout<< "Enter 1st list: \n";
    while (true) {
        cout<< "Enter the number: ";
        cin>>n;
        if (n==-9)
            break;
        else
            insert(&head1, n);
    }
    cout<< "Enter 2nd list: \n";
    while (true) {
        cout<< "Enter the number: ";
        cin>>n;
        if (n==-9)
            break;
        else
            insert(&head2, n);
    }
    print(head1);
    cout<< "\n";
    print(head2);
    head1 = merge(head1, head2);
    cout<< "\n";
    print(head1);
}

以上是关于c_cpp 合并两个已排序的链接列表的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 链接列表的合并排序

c_cpp 21.合并两个排序列表

c_cpp 合并两个排序列表,递归和迭代

c_cpp 21.合并两个排序列表 - 难度容易 - 2018.8.10

c_cpp 从已排序的链接列表中删除重复项

c_cpp 两个排序链接列表的交集