数据结构/PTA-两个有序链表序列的交集/链表

两个有序链表序列的交集


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

输入格式:

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

输出格式:

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

输入样例:

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

输出样例:

2 5

思路:使用数组很难保证不经过冗长的遍历,防止出现超时错误,选用链表


代码:

#include<bits/stdc++.h>
using namespace std;
typedef struct LNode //链表
{
int data;
struct LNode *next;
} LNode,*List;
void CreatList(List &s) //创建链表(输入数值)
{
LNode *p,*q;
s=(LNode*)malloc(sizeof(LNode));
q=s;
int x;


while(scanf("%d",&x)!=EOF)
{
if(x==-1)
{
return ;

}
p=(LNode*)malloc(sizeof(LNode));
p->next=NULL;
p->data=x;
q->next=p;
q=p;
}
}
int LocateElem(List s,int e)
{
int flag=0;
while(s!=NULL)
{
if(s->data==e)
{
flag++;
}
s=s->next;
}
return flag;
}
List Jlist(List s1,List s2) //合成:返回一个新链表
{
List S;
S=(LNode*)malloc(sizeof(LNode));
S->next=NULL;

LNode *z=S;
s1=s1->next;
s2=s2->next;

int e;
while(s1!=NULL)
{
e=s1->data;
if(LocateElem(s2,e)>0)
{
z->next=s1;
z=s1;

}
s1=s1->next;
}
return S;
}
void PrintfList(List s) //输出链表
{
if(s->next==NULL)
{
printf("NULL");
return ;
}
s=s->next;
while(s!=NULL)
{
if(s->next==NULL)
{
printf("%d",s->data);
}
else
{
printf("%d ",s->data);
}
s=s->next;
}
}
int main()
{
List s1,s2,S;
CreatList(s1);
CreatList(s2);
S=Jlist(s1,s2);
PrintfList(S);
}

 最近复习又看见了一个优化的方法,思路是一样的

2020-10-18

#include<stdio.h>
#include<stdlib.h>
typedef struct LNode
{
    int data;
    struct LNode* next;
} LNode, *List;
void CreatList(List &L)//构造链表
{
    LNode *p, *temp;
    L = (LNode* )malloc(sizeof(LNode));
    p = L;
    int t;
    while(scanf("%d", &t)!=EOF)
    {
        if(t == -1)
            return ;
        temp = (LNode*)malloc(sizeof(LNode));
        temp->next = NULL;
        temp->data = t;
        p->next = temp;
        p = temp;
    }
}
List MergeToInter(List L1, List L2)//利用归并排序的思路稍作修改
{
    List L;
    L = (LNode*)malloc(sizeof(LNode));
    L->next = NULL;
    LNode *p = L;
    L1 = L1->next;
    L2 = L2->next;
    while(L1!=NULL && L2!=NULL)
    {
        if(L1->data < L2->data)//L1后移
            L1 = L1->next;
        else if(L2->data < L1->data)//L2后移
            L2 = L2->next;
        else //相等则存入
        {
            p->next = L1;
            p = L1;
            L1 = L1->next;
            L2 = L2->next;
        }
    }

    return L;
}
void CoutList(List L)
{
    if(L->next == NULL)
    {
        printf("NULL");
        return ;
    }
    L = L->next;
    while(L != NULL)
    {
        if(L->next != NULL)
            printf("%d ", L->data);
        else
            printf("%d", L->data);
        L = L->next;
    }
}
int main()
{
    List L1, L2, L;
    CreatList(L1);
    CreatList(L2);
    L = MergeToInter(L1, L2);
    CoutList(L);
}

 https://www.cnblogs.com/Jie-Fei/p/10135649.html

原文地址:https://www.cnblogs.com/elegantcloud/p/13710001.html