7-1 两个有序链表序列的交集

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

输入格式:

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

输出格式:

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

输入样例:

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

输出样例:

2 5

 此题核心算法借鉴一个大佬的 。

在此演示链表做法

#include<stdio.h>
#include<stdlib.h>
struct st{
    int da;
    struct st *next;
};
 struct st *creat()  //建链表 用的尾插法
 {
     struct st *head=NULL,*ne=NULL,*tail=NULL;
     int n;
     while(1)
     {
         scanf("%d",&n);
         if(n==-1)
             break;
         ne=(struct st *)malloc(sizeof(struct st));
             ne->da=n;
         if(head==NULL)
             head=ne;
         else
             tail->next=ne;
         tail=ne;
         tail->next=NULL;
     }
     return head;
 }
struct st *cx(struct st *head1,struct st *head2)  //找交集
{
    struct st *ptr=NULL,*ptr1=NULL,*ptr2=NULL,*head=NULL,*tail=NULL;
    ptr1=head1;
    ptr2=head2;
    while(ptr1!=NULL&&ptr2!=NULL)
    {
        if(ptr1->da<ptr2->da)    //第一个链表角标后移
            ptr1=ptr1->next;
        else if(ptr1->da>ptr2->da)   //第二个链表角标后移
            ptr2=ptr2->next;
        else
        {
            ptr=(struct st *)malloc(sizeof(struct st));
            ptr->da=ptr1->da;
            if(head==NULL)
                head=ptr;
            else
                tail->next=ptr;
            tail=ptr;
            tail->next=NULL;
           ptr1=ptr1->next;
            ptr2=ptr2->next;
        }
    }
    return head;
}
int main()
{
     struct st *head1=NULL,*head2=NULL,*ptr=NULL,*head=NULL;
    head1=creat();
    head2=creat();
   head=cx(head1,head2);
    if(head==NULL)
        printf("NULL");
    else
    {
        for(ptr=head;ptr!=NULL;ptr=ptr->next)
        {
            printf("%d",ptr->da);
            if(ptr->next!=NULL)
                printf(" ");
        }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值