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

Posted

tags:

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

// https://www.geeksforgeeks.org/intersection-of-two-sorted-linked-lists/
#include <bits/stdc++.h>
using namespace std;

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

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

node* insert(node* head, int n) {
    if (head == NULL) {
        node* list= (node*)malloc(sizeof(node*));
        list->data = n;
        list->next = NULL;
        head = list;
        return head;
    }

    node* list= (node*)malloc(sizeof(node*));
    list->data = n;
    list->next = NULL;
    node* last= head;
    while (last->next != NULL )
        last = last->next;
    last->next = list;
    return head;
}

node* intersection (node *head1, node *head2) {
    node* head3 = NULL;
    while (head1 && head2) {
        if (head1->data == head2->data) {
            head3 = insert(head3, head1->data);
            head1 = head1->next;
            head2 = head2->next;
        }
        else if (head1->data < head2->data)
            head1 = head1->next;
        else if (head1->data > head2->data)
            head2 = head2->next;
    }
    return head3;
}

int main() {
    int n;
    node* head1 = NULL, *head2=NULL;
    cout<< "Enter the first list: \n";
    while (true) {
        cout<< "Enter the elements, and -999 to stop: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head1=insert(head1,n);
    }
    cout<< "Enter the second list: \n";
    while (true) {
        cout<< "Enter the elements, and -999 to stop: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head2=insert(head2,n);
    }
    print(head1);
    cout << "\n";
    print(head2);
    cout << "\n";
    node* head3 = intersection(head1,head2);
    print(head3);
}

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

c_cpp 交集,两个排序数组的并集

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

c_cpp 合并两个已排序的链接列表,使合并列表的顺序相反

c_cpp 链接列表的合并排序

两个已排序List求交集

c_cpp 通过更改链接对0,1和2的链接列表进行排序