(顺序表)判断两集合是否相等

#include<stdio.h>
typedef int A;
const int LIST_INIT_SIZE=100;
const int LISTINCRMENT=10;
typedef struct
{
	A *elem;
	int Length;
	int Listsize;
	int incrementsize;
}List;
void InitList(List &L,int maxsize=LIST_INIT_SIZE,int incresize=LISTINCRMENT)
{
	L.elem=new A[maxsize];
	L.Length=0;
	L.Listsize=maxsize;
	L.incrementsize=incresize;
}
int ListLength(List L)
{
	return (L.Length);
}
bool ListEmpty(List L)
{
	if(L.Length==0)
		return true;
	else
		return false;
}
void DestroyList(List &L)
{
	delete[]L.elem;
	L.Length=0;
	L.Listsize=0;
}
void ListDelete(List &L,int i,A &e) //删除第i个元素并用e返回其值
{
	A *p,*q;
	if((i<1)||(i>L.Length))
		printf("i值不合法\n");
	p=&(L.elem[i-1]);
	e=*p;
    q=L.Length+L.elem-1;
	for(++p;p<=q;p++)
		*(p-1)=*p;
	--L.Length;
}
int LocateElem(List L,A e)
{
	int *p;
	int i=1;
	p=L.elem;
	while(i<=L.Length&&*p++!=e)
		++i;
	if(i<=L.Length)
		return i;
	else
		return 0;
}
void GetElem(List &L,int i,A &e)
{
	if(i<1||i>L.Length)
		printf("i值不合法\n");
	e=L.elem[i-1];
}
void increment(List &L)
{
	A *a;
	int i;
	a=new A[L.Listsize+L.incrementsize];
	for(i=0;i<L.Length;i++)
		a[i]=L.elem[i];
	delete[]L.elem;
	L.elem=a;
	L.Listsize+=L.incrementsize;

}
void ListInsert(List &L,int i,A e)
{
	A *p,*q;
	if(i<1||i>L.Length+1)
		printf("i值不合法\n");
	if(L.Length>=L.Listsize)
		increment(L);
	q=&(L.elem[i-1]);
	for(p=&(L.elem[L.Length-1]);p>=q;p--)
		*(p+1)=*p;
	*q=e;
	++L.Length;
}
bool isequal(List La,List Lb)
{
	List Lc;
	int k,i,e;
	int La_len=ListLength(La);
	int Lb_len=ListLength(Lb);
	if(La_len!=Lb_len)
		return false;
	else
	{
		InitList(Lc);
		for(k=1;k<=La_len;k++)
		{
			GetElem(La,k,e);
			ListInsert(Lc,k,e);
		}
		bool found=true;
		for(k=1;k<=Lb_len&&found;k++)
		{
			GetElem(Lb,k,e);
			i=LocateElem(Lc,e);
			if(i==0)
				found=false;
			else
				ListDelete(Lc,i,e);
		}
		if(found&&ListEmpty(Lc))
			return true;
		else
			return false;
		//DestroyList(Lc);   //可要可不要
	}
}
int main()
{
	List a,b;
	InitList(a);
	InitList(b);
	int m,n,i;
	scanf("%d%d",&m,&n);
	for(i=0;i<m;i++)
	{
		scanf("%d",&a.elem[i]);
		a.Length++;
	}
	for(i=0;i<n;i++)
	{
		scanf("%d",&b.elem[i]);
		b.Length++;
	}
	bool f=isequal(a,b);
	if(f==true)
		printf("两集合相等\n");
	else
		printf("两集合不相等\n");
	return 0;
}

posted @ 2014-07-27 09:40  NYNU_ACM  阅读(330)  评论(0编辑  收藏  举报