PTA习题:进阶实验2-3.3 两个有序链表序列的交集 (20分)
已知两个非降序链表序列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 Node
{
int data;
struct Node *Next;
};
struct Node *Read();
struct Node * func(struct Node *L1, struct Node *L2); //找交集函数声明
void print(struct Node *L);
int main()
{
struct Node *L1, *L2, *L;
L1 = Read();
L2 = Read();
L = func(L1, L2);
print(L);
return 0;
}
struct Node *Read()
{
struct Node *head, *p, *tail;
int num;
head = NULL;
tail = head;
scanf("%d", &num);
while (num != -1)
{
p = (struct Node *)malloc(sizeof(struct Node));
p->data = num;
p->Next = NULL;
if (head == NULL) { head = p; tail = p; }
else { tail->Next = p; tail = p; }
scanf("%d", &num);
}
return head;
}
struct Node * func(struct Node *L1, struct Node *L2)
{
struct Node *head, *p, *q, *m, *tail;
head = NULL; tail = head;
p = L1;
q = L2;
if (L1 != NULL && L2 != NULL)
{
while (p != NULL && q != NULL)
{
if (p->data > q->data)
{
q = q->Next;
}
else if (p->data < q->data)
{
p = p->Next;
}
else if (p->data == q->data)
{
m = (struct Node *)malloc(sizeof(struct Node));
m->data = p->data;
m->Next = NULL;
if (head == NULL)
{
head = m;
tail = m;
}
else
{
tail->Next = m;
tail = m;
}
p = p->Next;
q = q->Next;
}
}
}
return head;
}
void print(struct Node *L)
{
struct Node *p;
if (L == NULL) { printf("NULL"); }
else {
for (p = L; (p->Next) != NULL; p = p->Next)
{
printf("%d ", p->data);
}
printf("%d", p->data);
}
}
程序二:该程序最后一个大规模数据测试点运行超时,因为使用了两重嵌套的循环
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *Next;
};
struct Node *Read();
struct Node * func(struct Node *L1, struct Node *L2);
void print(struct Node *L);
int main()
{
struct Node *L1, *L2, *L;
L1 = Read();
L2 = Read();
L = func(L1, L2);
print(L);
return 0;
}
struct Node *Read()
{
struct Node *head, *p, *tail;
int num;
head = NULL;
tail = head;
scanf("%d", &num);
while (num != -1)
{
p = (struct Node *)malloc(sizeof(struct Node));
p->data = num;
p->Next = NULL;
if (head == NULL) { head = p; tail = p; }
else { tail->Next = p; tail = p; }
scanf("%d", &num);
}
return head;
}
struct Node * func(struct Node *L1, struct Node *L2)
{
struct Node *head, *p, *q, *m, *tail;
head = NULL; tail = head;
if (L1 != NULL && L2 != NULL)
{
for (p = L1; p != NULL; p = p->Next)
{
for (q = L2; q != NULL; q = q->Next)
{
if (p->data == q->data)
{
m = (struct Node *)malloc(sizeof(struct Node));
m->data = p->data;
m->Next = NULL;
if (head == NULL)
{
head = m;
tail = m;
}
else
{
tail->Next = m;
tail = m;
}
}
}
}
}
return head;
}
void print(struct Node *L)
{
struct Node *p;
if (L == NULL) { printf("NULL"); }
else {
for (p = L; (p->Next) != NULL; p = p->Next)
{
printf("%d ", p->data);
}
printf("%d", p->data);
}
}