工程实践:求两个有序集合的并集依然有序之数组法

#include
#include
#define TRUE 1
#define FALSE 0
#define ERROR 0
#define OVERFLOW -1
#define OK 1;
#define LISTINCREMENT 10
typedef int Status; /**Status是函数类型,其值是函数结果状态代码,如OK等**/
typedef int ElemType; /*ElemType类型根据实际情况而定,这里假设为char*/
#define LIST_INIT_SIZE 100


#define MAXSIZE 50          /* 存储空间初始分配量 */
typedef struct
{
	
	ElemType data[MAXSIZE];  /* 数组,存储数据元素 */
	int length;              /* 表当前有效长度 */
}SqList;  
SqList La,Lb,Lc;



Status GetElem(SqList L,int i,ElemType *e)
{
	
	/* 初始条件:数组表示的表L已存在,1≤i≤ListLength(L) */
	/* 操作结果:用e返回L中第i个数据元素的值,
	注意i是指位置,第1个位置的数组是从0开始 */
	
	if(L.length==0 || i<1 || i>L.length)
		return ERROR;
	*e=L.data[i-1];
	return OK;
}


Status ListEmpty(SqList L)
{ 
	
	/* 初始条件:数组表示的表L已存在。*/
	/* 操作结果:若L为空表,则返回TRUE,否则返回FALSE。 */
	
	if(L.length==0)
		return TRUE;
	else
		return FALSE;
}


int ListLength(SqList L)
{
	return L.length;
}


Status ListInsert(SqList *L,int i,ElemType e)
{
	ElemType *p,*q;
	int j=0;
	
	while((*L).data[j])
	{
		if(e==(*L).data[j]) return FALSE;
		j++;
	}
	q=&((*L).data[i-1]);
	for(p=&((*L).data[(*L).length-1]);p>=q;--p) *(p+1)=*p;
	*q=e;
	++(*L).length;
	return OK;
}


void MergeList(SqList La, SqList Lb, SqList *Lc) 
{ 
	/* 已知表La和Lb中的数据元素按值非递减排列。 */
	/* 归并La和Lb得到新的表Lc,Lc的数据元素也按值非递减排列 */
	
	int i,j,k;
	i=j=1;k=0;
	int La_len=ListLength(La);
	int Lb_len=ListLength(Lb);
	int ai,bj;
	
	while(i<=La_len&&j<=Lb_len)          /* 表La和表Lb均非空 */
	{
		GetElem(La,i,&ai);
		GetElem(Lb,j,&bj);
		if(ai<=bj)
		{
			if(!ListInsert(Lc,++k,ai)) k--;
			++i;
		}
		else
		{
			if(!ListInsert(Lc,++k,bj)) k--;
			++j;
		}
	}
	while(i<=La_len)                /* 表La非空且表Lb空 */
	{
		GetElem(La,i++,&ai);
		ListInsert(Lc,++k,ai);
	}
	while(j<=Lb_len)                /* 表Lb非空且表La空 */
	{
		GetElem(Lb,j++,&bj);
		ListInsert(Lc,++k,bj);
	}
}


void CreateLise(SqList *L)
{
	ElemType ch;
	char c='1';
	int inlist=FALSE,j;
	while(c!='\n')
	{
		scanf("%d",&ch);
		scanf("%c",&c);
		
		for(j=0;j<(*L).length;j++)
		{
			if(ch==(*L).data[j])
			{
				inlist=TRUE;
				break;
			}
			else inlist=FALSE;
		}
		if(!inlist) ListInsert(L,(*L).length+1,ch);
	}
	
	
}


void Print_Sq(SqList L)
{
	int i;
	for(i=0;i

你可能感兴趣的:(算法)