2-12. 两个有序链表序列的交集(20)
时间限制
400 ms
内存限制
64000 kB
代码长度限制
8000 B
判题程序
Standard
已知两个非降序链表序列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 |
链表标准代码:
#include <stdio.h>
#include <stdlib.h>
#define LEN (struct node*)malloc(sizeof(struct node))
struct node
{
int num;
struct node *next;
};
node *creat()
{
node *t,*p,*head;
int n,i=0;
p=LEN;
t=p;
scanf("%d",&p->num);
head=NULL;
p->next=NULL;
while(p->num!=-1){
if(!i){
head=p;
i=1;
}
else
t->next=p;
t=p;
p=LEN;
scanf("%d",&p->num);
p->next=NULL;
}
return head;
}
node *jiao(node *head1,node *head2)
{
node *head,*t,*p1,*p2,*p;
int flag=0;
head=NULL;
t=head;
p1=head1;
p2=head2;
while(p1&&p2){
if(p1->num > p2->num)
p2=p2->next;
else if(p1->num < p2->num)
p1=p1->next;
else{
p=LEN;
p->num=p1->num;
p->next=NULL;
if(!flag){
head=p;
flag=1;
}
else
t->next=p;
t=p;
p1=p1->next;
p2=p2->next;
}
}
return head;
}
void print(node *head)
{
struct node *p;
p=head;
int i=0;
while(p!=NULL){
if(i)
printf(" ");
i=1;
printf("%d",p->num);
p=p->next;
}
if(!i)
printf("NULL");
printf("\n");
}
int main()
{
node *head1,*head2;
head1=creat();
head2=creat();
head1=jiao(head1,head2);
print(head1);
return 0;
}vector解法:
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
vector<int> h1,h2,h3;
void creat()
{
int i,j,n;
for(i=0;i<2;i++)
{
while(1)
{
scanf("%d",&n);
if(n==-1)
{
break;
}
if(i)
{
h2.push_back(n);
}
else
{
h1.push_back(n);
}
}
}
}
void jiao()
{
int i,j,a,b;
a=h1.size();
b=h2.size();
i=j=0;
while(i!=a&&j!=b)
{
if(h1[i]<h2[j])
{
i++;
}
else if(h1[i]>h2[j])
{
j++;
}
else{
h3.push_back(h1[i]);
i++;
j++;
}
}
}
void print()
{
int i,a;
a=h3.size();
if(!a)
{
printf("NULL\n");
}
else{
for(i=0;i<a;i++)
{
if(i)
{
printf(" ");
}
printf("%d",h3[i]);
}
printf("\n");
}
}
int main()
{
creat();
jiao();
print();
return 0;
}
该博客介绍如何找到两个非降序链表序列的交集,提供输入格式和输出格式说明,并给出了样例输入和输出。
3894

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



