题目链接:http://pat.zju.edu.cn/contests/ds/2-12
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式说明:
输入分2行,分别在每行给出由若干个正整数构成的非降序序列,用-1表示序列的结尾(-1不属于这个序列)。数字用空格间隔。
输出格式说明:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出“NULL”。
样例输入与输出:
| 序号 | 输入 | 输出 |
| 1 | 1 2 5 -1 2 4 5 8 10 -1 | 2 5 |
| 2 | 1 3 5 -1 2 4 6 8 10 -1 | NULL |
| 3 | 1 2 3 4 5 -1 1 2 3 4 5 -1 | 1 2 3 4 5 |
| 4 | 3 5 7 -1 2 3 4 5 6 7 8 -1 | 3 5 7 |
| 5 | -1 10 100 1000 -1 | NULL |
PS:
和上一题思路一样,只需要稍加变化即可!同样用vector 233333……
代码一如下(链表):
#include <cstdio>
#include <cstring>
#include <malloc.h>
#define LEN sizeof(struct node)
struct node
{
int x;
struct node *next;
};
int flag = 0;
struct node *creat()
{
struct node *p1, *p2, *head1;
p1=p2=head1=(struct node*)malloc(LEN);
scanf("%d",&p1->x);
head1 = NULL;
int n = 0;
while(p1->x != -1)
{
n++;
if(n == 1)
head1 = p1;
else
p2->next = p1;
p2 = p1;
p1 = (struct node *)malloc(LEN);
scanf("%d",&p1->x);
}
p2->next = NULL;
return head1;
}
void findd(struct node *p1, struct node *p2)
{
while(p1!=NULL && p2!=NULL)
{
if(p1->x < p2->x)
{
p1 = p1->next;
}
else if(p1->x > p2->x)
{
p2 = p2->next;
}
else
{
if(flag)
printf(" %d",p1->x);
else
printf("%d",p1->x);
flag++;
p1 = p1->next;
p2 = p2->next;
}
}
if(flag == 0)
printf("NULL\n");
}
int main()
{
struct node *p, *head1, *head2;
head1 = creat();
head2 = creat();
findd(head1, head2);
// print(p);
return 0;
}
代码二如下(vector):
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#include <vector>
vector<int>a, b, c;
int main()
{
int tt;
while(1)
{
scanf("%d",&tt);
if(tt == -1)
break;
a.push_back(tt);
}
while(1)
{
scanf("%d",&tt);
if(tt == -1)
break;
b.push_back(tt);
}
int len1 = a.size();
int len2 = b.size();
int i = 0, j = 0;
while(i < len1 && j < len2)
{
if(a[i] == b[j])
{
c.push_back(a[i]);
i++,j++;
}
else if(a[i] < b[j])
{
// c.push_back(a[i]);
i++;
}
else
{
// c.push_back(b[j]);
j++;
}
}
int len3 = c.size();
if(!len3)
{
printf("NULL\n");
// return 0;
}
else
{
int flag = 0;
for(int i = 0; i < len3; i++)
{
if(flag)
{
printf(" %d",c[i]);
}
else
{
printf("%d",c[i]);
flag = 1;
}
}
printf("\n");
}
return 0;
}

3324

被折叠的 条评论
为什么被折叠?



