求两个链表的交集

/*已知两个链表A和B分别表示两个集合,其元素递增排列。编制函数,求A与B的交集,并存放于A链表中*/
#include
#include
typedef int ElemType;
typedef struct LNode{
	ElemType data;
	struct LNode *next;
}LNode,*LinkList;

LinkList createHeadList(LinkList &L)
{
	LNode *r;
	L = (LinkList)malloc(sizeof(LNode));
	r = L;
	ElemType x;
	scanf("%d",&x);
	while(x != 9999)
	{
		LNode *s = (LNode*)malloc(sizeof(LNode));
		s->data = x;
		r->next = s;
		r = s;
		scanf("%d",&x);
	}
	r->next = NULL;
	return L;
}

LinkList combinCommon(LinkList &A,LinkList &B)
{
	LNode *pa = A->next;
	LNode *pb = B->next;
	LNode *u;
	LNode *r = A;
	while(pa && pb)
	{
		if(pa->data < pb->data)
		{
			u = pa;
			pa = pa->next;
			free(u);
		}
		if(pa->data > pb->data)
		{
			u = pb;
			pb = pb->next;
			free(u);
		}
		else{
			r->next = pa;
			r = pa;
			pa = pa->next;
			u = pb;
			pb = pb->next;
			free(u);
		}
	}
	while(pa)
	{
		u = pa;
		pa = pa->next;
		free(u);

	}
	while(pb)
	{
		u = pb;
		pb = pb->next;
		free(u);

	}
	r->next = NULL;
	free(B);
	return A;
}

bool printList(LinkList L)
{
	LNode *p = L->next;
	while(p)
	{
		printf("%d ",p->data);
		p = p->next;
	}
	printf("\n");
	return true;
}

void main()
{
	LinkList A,B;
	printf("创建链表A:");
	createHeadList(A);
	printf("创建链表B:");
	createHeadList(B);
	combinCommon(A,B);
	printf("After:\n");
	printList(A);
}

你可能感兴趣的:(链表,链表,c语言,数据结构)