求新的集合 A=AUB(顺序表)

#include<stdio.h>
typedef int A;
const int LIST_INIT_SIZE=100;
const int LISTINCREMENT=10;
typedef struct
{
	A *elem;
	int length;
	int listsize;
	int incrementsize;

}List;
void InList(List &L,int maxsize=LIST_INIT_SIZE,int incresize=LISTINCREMENT)
{
	L.elem=new A[maxsize];
	L.length=0;
	L.incrementsize=maxsize;
	L.listsize=incresize;
}
void ListDelete(List &L,int i,A &e)
{
	A *p,*q;
	if((i<1)||(i>L.length))
		printf("i值不合法\n");
	p=&(L.elem[i-1]);
	e=*p;
	q=L.elem+L.length-1;
	for(++p;p<=q;++p)
		*(p-1)=*p;
	--L.length;
}
void DestroyList(List &L)
{
	delete[] L.elem;
	L.listsize=0;
	L.length=0;
}
void increment(List &L)
{
	A *a,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)
{
	if(i<1||i>L.length+1)
		printf("i值不合法\n");
	A *p,*q;
	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;
}
int LocateElem(List L,A e)
{
	A *p;
	int i=1;
	p=L.elem;
	while(i<=L.length&&*p++!=e)
		++i;
	if(i<=L.length) return i;
	else return 0;
}
bool ListEmpty(List L)
{
	if(L.length==0)
		return true;
	else
		return false;

}
int ListLength(List L)
{
	return (L.length);
}
void union1(List &La,List &Lb)
{
	A e,La_len;
	La_len=ListLength(La); //读取线性表La的长度
	while(!ListEmpty(Lb))
	{
		ListDelete(Lb,1,e); //删除线性表Lb的第一个数据元素并将其赋给e
		if(!LocateElem(La,e))        //若La!=e则将e插入La中
			ListInsert(La,++La_len,e);
	}
	DestroyList(Lb);   //直到线性表Lb的长度为空时销毁Lb。
}
int main()
{
	List a , b ;
	InList(a);  //  进行初始化 a.length=0;
	InList(b);  //             b.length=0;
	int i;
	for(i=1;i<5;i++)
	{
		a.elem[i-1] = i ;
		a.length++;  //是为了在此基础上插入新的元素.
	}
	b.elem[0] = 1 ;
	b.elem[1] = 4 ;
	b.elem[2] = 8 ;
	b.length=3;  //是判断最终b为不为空
	union1(a,b);
	for(i=0;i<a.length;i++)
		printf("%d ",a.elem[i]);
	printf("\n") ;
	return 0;
}

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