7-1 两个有序链表序列的交集 (20分)
已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。
输入样例:
1 2 5 -1
2 4 5 8 10 -1
输出样例:
2 5
思路:读入两个链表后,进入查重代码部分,如果链表1中的data大于链表2中的data,则将链表1向后移动一位,若链表2中的data大于链表1中的data,则将链表2向后移动一位,如果两者相同,则将链表1或者2的地址存到新的链表3中,并将链表1与链表2都后移一位(这里特别注意一定要两个都要后移,不然一个测试点过不去,因为比如链表1为5 5 6 链表2为5 6,如果只移动链表1,则会输出5 5 6,而正确答案为5 6)具体代码如下所示:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define LEN sizeof(struct node)
struct node
{
int x;
struct node *next;
};
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;
}
struct node *findd(struct node *p1, struct node *p2)
{
struct node *p3 ,*head3;
int n=0;
head3=NULL;
while(p1!=NULL && p2!=NULL)
{
if(p1->x<p2->x&&p1!=0 && p2!=0)
p1=p1->next;
else if(p1->x>p2->x&&p1!=0 && p2!=0)
p2=p2->next;
else if(p1->x==p2->x)
{
n++;
if(n == 1)
{
head3 = p1;
p3=head3;
}
else
p3->next=p1;
p3=p1;
p1=p1->next;
p2=p2->next;
}
p3->next=NULL;
}
return head3;
}
void print(struct node *head)
{
struct node *p;
p = head;
int n = 0;
int flag = 0;
while(p!=NULL)
{
flag = 1;
n++;
if(n == 1)
printf("%d",p->x);
else
printf(" %d",p->x);
p = p->next;
}
if(!flag)
printf("NULL\n");
}
int main()
{
struct node *p, *head1, *head2;
head1 = creat();
head2 = creat();
p = findd(head1, head2);
print(p);
return 0;
}