zoukankan      html  css  js  c++  java
  • 进阶实验2-3.3 两个有序链表序列的交集 (20分)

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

    输入格式:

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

    输出格式:

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

    输入样例:

    1 2 5 -1
    2 4 5 8 10 -1
    
     

    输出样例:

    2 5

    #include<iostream>
    using namespace std;
    typedef struct LNode
    {
        int data;
        struct LNode *next;
    
    }LNode,*List;
    
    void creat(List &l1)//传入一个指向链表结点的指针,以这个指针为头结点,构建链表
    {//注意:这里必须传入引用,因为会改变l1指向的值,一开始传入的是一个空指针,后来指向了构造的结点,改变了l1的值,所以要用reference
        List p,temp;
        p = (LNode*)malloc(sizeof(LNode));
        l1 = p;
    
        int e;
        while(scanf("%d",&e)!=EOF)
        {
            if(e == -1)
                return;
            temp = (LNode*)malloc(sizeof(LNode));
            temp ->data = e;
            temp ->next = NULL;
            p->next = temp;
            p = p->next;
        }
    }
    
    List mergeTOInter(List l1,List l2)
    {
        List l;//l指向表头
        l = (List)malloc(sizeof(LNode));//先构造头节点
        List p = l;
        l->next = NULL;
    
        l1 = l1->next;//l1 and l2 都有头节点
        l2 = l2->next;
    
        while(l1!=NULL&&l2!=NULL)//l1 and l2 不为空,找到它们中相同的元素的结点,使p指向这个结点,
        {//
            if(l1->data < l2->data)
                l1 = l1->next;
            else if(l1->data > l2->data)
                l2 = l2->next;
            else
            {
                p->next = l1;
                l1 = l1->next;
                l2 = l2->next;
    
                p = p->next;
            }
        }
    
        return l;//
    }
    void countlist(List l)
    {//打印链表的data
    
        List p = l;
        p = p->next;
        if(p==NULL)
        {
            printf("NULL");
            return;
        }
        while(p)
        {
            if(p->next != NULL)
                printf("%d ",p->data);
            else
                printf("%d",p->data);
    
            p = p->next;
        }
    }
    int main()
    {
        List l1, l2, l;
        creat(l1);
        creat(l2);
        l = mergeTOInter(l1,l2);
        
        countlist(l);
    
        return 0;
    }
  • 相关阅读:
    「JOISC 2020 Day3」收获
    $ ext{Min25}$筛
    [做题记录-图论] [NEERC2017]Journey from Petersburg to Moscow [关于处理路径前$k$大的一种方法]
    [复习笔记]一些有意思的解法技巧 (转 Dpair
    [比赛记录] CSP2021-S 题解
    [转]C++学习心得
    Sigmoid function in NN
    Kernel Regression from Nando's Deep Learning lecture 5
    Python codes
    php中mail()改用msmtp发送邮件
  • 原文地址:https://www.cnblogs.com/qinmin/p/12496079.html
Copyright © 2011-2022 走看看