使用单链表实现一般集合的并集问题(最后表中无相同元素)

#include<stdio.h>
#include<stdlib.h>
#define N 5
#define M 3

typedef struct LNode
{
	int data;
	struct LNode *next;	
}LNode,*LinkList;

LNode *CreateList(int n);
void GetElem(LNode *list,int *e);
int IsLocate(LinkList LA,int e);
void InsertElem(LinkList LA,int e);
 
int main()
{
	LinkList LA,LB;
	
	//创建链表LA与LB
	LA=CreateList(N);
	LB=CreateList(M);
	
	int i;
	int e;
	LB=LB->next;
	for(;LB;LB=LB->next)
	{
		//遍历链表LB
		GetElem(LB,&e); 
		//遍历链表LA 判断e是否存在于LA中 
		if(!IsLocate(LA,e))//不存在,返回 0
			InsertElem(LA,e);  //不存在,把e插入LA 
	}
	
	LNode *p;
	for(p=LA->next;p;p=p->next)
		printf("%3d",p->data);
	
	return 0; 
}

LNode *CreateList(int n)
{
	LinkList L;
	LNode *p,*r;
	
	L=(LinkList)(malloc(sizeof(LNode)));
	L->next=NULL;
	r=L;
	
	printf("Enter %d numbers: ",n);
	int i;
	for(i=0;i<n;i++)
	{
		p=(LinkList)(malloc(sizeof(LNode)));
		scanf("%d",&p->data);
		
		r->next=p;
		p->next=NULL;
		r=p;
	}
	
	return L;
}

void GetElem(LNode *list,int *e)
{
	if(!list)
	{
		printf("ERROR\n");
		exit(0);
	}
	
	*e=list->data;
}

int IsLocate(LinkList LA,int e)
{
	LNode *p;
	
	for(p=LA->next;p;p=p->next)
		if(p->data==e)
			return 1;
			
	return 0;
}

void InsertElem(LinkList LA,int e)
{
	LNode *p;
	
	p=(LinkList)(malloc(sizeof(LNode)));
	p->next=NULL;
	p->data=e;
	
	//找到末结点
	for(;LA->next;LA=LA->next);
	LA->next=p;
}

猜你喜欢

转载自blog.csdn.net/Huayra221/article/details/81115936