顺序表合并

合并LA,LB两个线性表到线性表LC中:

LinearList.h

#include <stdio.h>
#include <stdlib.h>
#define MaxSize 20

typedef struct
{
	int elem[MaxSize];
	int length;
}SqList;

void initList(SqList* &L)
{
	L = (SqList *)malloc(sizeof(SqList));
	L->length = 0;
}

void Destory(SqList* &L)
{
	free(L);
}

int ListEmpty(SqList *L)
{
	return (L->length==0);
}

int ListLength(SqList *L)
{
	return L->length;
}

void DispList(SqList *L)
{
	int i=0;
	if(ListEmpty(L)) return;
	for(;i<L->length;i++)
	{
		printf("%d ",L->elem[i]);
	}
	printf("\n");
}

int GetElem(SqList *L, int i, int &e)
{
	if(i<1 && i>L->length) return 0;
	e = L->elem[i-1];
	return 1;
}

int LocateElem(SqList *L, int e)    //是为了寻找第一个值域与e相等的元素的次序,所以要加1
{
	int i = 0;
	while(i<L->length && L->elem[i]!= e)
		i++;
	if(i>= L->length)
		return 0;
	else
		return i+1;
}

int inserList(SqList* &L,int i, int e)
{
	int j;
	if(i<1 && i>L->length +1)
		return 0;
	i--; //将顺序表位序转换为elem下标
	for (j=L->length;j>i;j--)
	{
		L->elem[j] = L->elem[j-1];
	}
	L->elem[i] = e;
	L->length++;
	return 1;
}

 Union.cpp

#include <stdio.h>
#include "LinearList.h"


void Union(SqList *LA, SqList *LB, SqList *&LC)
{
	int lena,lenb;
	int e;
	initList(LC);
	for(int i=1;i<=ListLength(LA);i++)
	{
		GetElem(LA,i,e);
		//printf("e = %d\n",e);
		inserList(LC,i,e);
	}
	lena = ListLength(LA);
	lenb = ListLength(LB);
	printf("lena = %d lenb = %d\n",lena,lenb);
	for(int j=1;j<=lenb;j++)
	{
		GetElem(LB,j,e);
// 		printf("e = %d\n",e);
// 		printf("LocateElem = %d\n",LocateElem(LA,e));
		if(!LocateElem(LA,e))
			inserList(LC,++lena,e);
	}
}
int main(void)
{
	SqList *LA,*LB,*LC;
	initList(LA);
	initList(LB);
	printf("please input the length of LA : \n");
		scanf("%d",&LA->length);
	printf("please input the LA set : \n");
	for(int i=0;i<LA->length;i++)
		scanf("%d",&LA->elem[i]);


	printf("please input the length of LB : \n");
		scanf("%d",&LB->length);
	printf("please input the LB set : \n");
	for(int j=0;j<LB->length;j++)
		scanf("%d",&LB->elem[j]);
	Union(LA,LB,LC);
	printf("LC length = %d\n",ListLength(LC));
	DispList(LC);
	return 0;
}
 

你可能感兴趣的:(顺序)