交集(数学和测试点的区别)

3-2-6 链表 两个有序链表序列的交集 

--------------------------------------------------------------------------------------------------------------------------- 

这个点是经过了长时间折磨才发现的,进来看看哦,防止以后这个点错了卡100年

---------------------------------------------------------------------------------------------------------------------------

 已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。

输入格式:

输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用1表示序列的结尾(1不属于这个序列)。数字用空格间隔。

输出格式:

在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL

输入样例:

1 2 5 -1
2 4 5 8 10 -1
 
结尾无空行

输出样例:

2 5
 
结尾无空行
 
#include<iostream>
#include<malloc.h>
#include<vector>
using namespace std;

typedef struct num* list;

struct num {
    int x;
    struct num* next;
};

list cinf() {
    list head = NULL;
    list tail = head;
    int n;
    cin >> n;
    if(n==-1){
        return NULL;
    }
    while (n != -1) 
    {
        list p = (list)malloc(sizeof(struct num));
        p->x = n;
        if (head == NULL) {
            head = p;
            tail = p;
            head->next = NULL;
        }
        else {
            tail->next = p;
            tail = p;
        }
        cin >> n;
    }
    tail->next = NULL;
    return head;
}

void compare(list& head1, list& head2) {
    list t1 = head1;
    list t2 = head2;
    if (head1 == NULL || head2 == NULL) {
        cout << "NULL";
        return;
    }
    list head = (list)malloc(sizeof(struct num));
    head->next = NULL;
    list tail = head;
    t1=head1;
    while (t1) {
        t2=head2;
        while (t2) {
            if (t2 && t2->x == t1->x) {
                list p = (list)malloc(sizeof(struct num));
                p->x = t1->x;
                t2->x=-1;      //这一步可以说是这题最恶心的点了,下面细说
                tail->next = p;
                tail = p;
                break;
            }
            t2 = t2->next;
            if (t2 && t2->x > t1->x) {
                break;
            }
        }
        t1 = t1->next;
    }
    tail->next=NULL; 
    int flag = 0;
    head = head->next;
    if(head==NULL){
        cout <<"NULL";
        return;
    }
    while (head) 
    {
            if (flag == 1) {
            cout << " ";
        }
            cout << head->x;
            flag = 1;
        head=head->next;
    }
}

int main() {
    list head1 = cinf();
    list head2 = cinf();
    compare(head1, head2);
}

 

---------------------------------------------------------------------------------------------
这题的代码比较的常规,没什么可讲的,但是测试点就很让人烦躁
这个测试点叫大规模数据
大家都知道,集合在数学里的定义是不可以有重复的数据的
但是在pta中,是可以存在的
这样就引申出了一个问题,交集里的数据是几个呢
假设
a:1 1 1 1 1 2 3 5 6 -1
b:1 1 1 2 4 7 8 -1
那交集c是什么呢
A.  c:1 1 1 1 1 2 
B.  c:1 2
C.  c:1 1 1 2
-----------------------------
 
 
 
 
 
 
 
-----------------------------
 答案是:C
a中1出现5次,b中1出现3次,
交集
顾名思义
就是重复的部分
那就是3次
所以应输出
1 1 1 2
 
这时候就要利用非数据-1来做事了
每次抵消掉一个数据,就可以把他改成-1,不会被再次调用(绝对不是因为我懒得释放空间)
就是这样🥱
晚安兄弟们😴
 
posted @ 2021-11-10 22:43  星落化尘丶  阅读(281)  评论(0)    收藏  举报