《数据结构》严蔚敏 算法2.1代码实现

题目要求实现: A= AUB
参考博客:https://blog.csdn.net/sunshine_rebrith/article/details/78310545

用线性表的顺序结构来表示(数组实现)

#include
#include
#define TRUE 1
#define FALSE 0
#define OVERFLOW -1
#define OK 1
#define ERROR 0


typedef int Status;
typedef int ElemType;


#define LIST_INIT_SIZE 10
#define LIST_INCREMENT 2


//stored in array 
//complete task: A = A U B
//A=(3,5,8,11)
//B=(2,6,8,9,11,15,20)

typedef struct list
{
	ElemType *elem;
	int length;
	int listsize;

}List;


Status
InitList(List * L)
{
	(*L).elem = (ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
	if(!(*L).elem)
		exit(OVERFLOW);
	(*L).length = 0;
	(*L).listsize = LIST_INIT_SIZE;

	return OK;
	
}

int
Listlength(List L)
{
	return L.length;

}

Status
GetElem(List L,int i,ElemType * e)
{
	if(i < 1 || i > L.length)
		exit(ERROR);
	*e = *(L.elem+i-1); // because of it's array
	return OK;
}

int
LocateElem(List L,ElemType e,Status(*compare)(ElemType,ElemType)) //attention the function here should write like this
{
	ElemType *p;
	int i = 1;
	p = L.elem;
	while(i <= L.length && !compare(*p++,e))
		++i;
	if(i<=L.length)
		return i;
	else
		return 0;

}

Status 
ListInsert(List * L,int i,ElemType e)
{
	ElemType *newbase,*q,*p;
	if( i<1||i>(*L).length+1 )
		return ERROR;
	if((*L).length >= (*L).listsize)
	{
		newbase = (ElemType *)realloc((*L).elem,((*L).listsize + LIST_INCREMENT) *sizeof(ElemType));
		if(!newbase)
			exit(OVERFLOW);
		(*L).elem = newbase;
		(*L).listsize += LIST_INCREMENT;
	}

	q = (*L).elem+i-1;
	for( p = (*L).elem + (*L).length-1 ; p >= q; --p )
	{
		*(p+1) = *p;
	}

	*q = e;
	++(*L).length;
	return OK;
}

//the subsrcipt is from 0
Status
define_create(List *L,int n)
{
	int i,j;
	ElemType e;
	InitList(L);
	printf("please enter %d elements: ",n);
	scanf("%d",&e);
	ListInsert(L,1,e);//if don't write like this divided,we can't get the result.
	for(i = 1;i

《数据结构》严蔚敏 算法2.1代码实现_第1张图片

你可能感兴趣的:(数据结构&算法)