求两个链表的交集

很简单 慢慢看能看懂。

#include 
#include 
#define len sizeof(struct List)
 struct List{//?????
	int x;
	struct List *next;
};
struct List * creat()
{
	struct List *head,*p1,*p2;
	int n=0;
	p1=p2=(struct List *)malloc(len);
	while(1)
	{
		scanf("%d",&p1->x);
		if(p1->x==-1)
		break;
		n=n+1;
		if(n==1) head=p1;
		else p2->next=p1;
		p2=p1;
		p1=(struct List *)malloc(len);
	}
	p2->next=NULL;
	return head;
}
bool IsExit_a(int y,struct List *head)
{
	while(head!=NULL)
	{
		if(head->x==y)
		return true;
		head=head->next;
	}	
	return false;
}
int main()
{
	struct List *head_a,*head_b,*head_temp,*head,*head_c;
	printf("请输入链表A元素(以-1结束):");
	head_a=creat();
	printf("请输入链表A元素(以-1结束):");
	head_b=creat();
	printf("\n");
	head=head_c=(struct List *)malloc(len);
	int n=0;
	while(head_b!=NULL)
	{
		if(IsExit_a(head_b->x,head_a))
		{
			if(n==0)
			{
				head_c->x=head_b->x;
				head_c->next=NULL;
				n++;
			}
			else
			{
				head_temp=(struct List *)malloc(len);
				head_temp->x=head_b->x;
				head_temp->next=NULL;
				head_c->next=head_temp;	
				head_c=head_temp;
			}
		}
		head_b=head_b->next;
	}
	printf("链表A,B的交集为:");
	while(head!=NULL)
	{
		printf("%d ",head->x);
		head=head->next;
	}
	printf("\n"); 
	return 0;
}


你可能感兴趣的:(【数据结构】,Acm竞赛)