第二周作业——数据结构

自行组织文件

函数声明,宏,结构体声明等等

#define OVERFLOW -2
#define ERROR 0
#define TRUE 1
#define FALSE 0

#define MAX_SIZE 100


typedef int ElemType;
typedef int Position;
typedef int bool;

typedef struct
{
	ElemType Data[MAX_SIZE];
	Position Last;
}*List;

List make_empty_list();
ElemType find_kth_list(List L, int i);
Position find_list(List L, ElemType e);
bool insert_list(List L, ElemType e, int i);
bool delete_list(List L, int i);
int length_list(List L);
void print_list(List L);

函数定义

#define _MY

List make_empty_list()
{
	List L;
	L = (List)malloc(sizeof(*L));
	if (!L)
	{
		exit(OVERFLOW); //溢出
	}
	L->Last = -1;
	return L;
}
ElemType find_kth_list(List L, int i)
{
	return L->Data[i - 1];
}
Position find_list(List L, ElemType e)
{
	int i;
	for (i = 0; i < L->Last + 1; ++i)
	{
		if (L->Data[i] == e)
		{
			return i+1;
		}
	}
	return ERROR;
}
bool insert_list(List L,ElemType e,int i)
{
	if (L->Last == MAX_SIZE - 1)  //L已经满了
		return FALSE;
	if (i<1 || i > L->Last + 1 + 1) //i的数值不合法
		return FALSE;
#ifdef _MY    //     ------>①   ①②只有一段会被编译
	ElemType *q, *p;
	p = L->Data + i - 1;  //指向待替换位置
	for (q = L->Data + L->Last; q >= p; --q)
		*(q + 1) = *p;
	*p = e;
	
#else			------>②
	int j;
	for (j = L->Last; j >= i - 1; --j) //j可以等于i-1
	{
		L->Data[j + 1] = L->Data[j];
	}
	L->Data[i - 1] = e;
#endif // !_MY     
	L->Last++;
	return TRUE;
}
bool delete_list(List L, int i)
{
	if (i<1 || i>L->Last + 1) //参数不合法
		return FALSE;
#ifdef _MY
	ElemType *q;

	for (q = L->Data + i - 1; q <= L->Data + L->Last-1; ++q)
		*q = *(q + 1);
#else
	int j;
	for (j = i; j <= L->Last; j++)
		L->Data[j - 1] = L->Data[j];
	
#endif // _MY
	L->Last--;
	return TRUE;


}
int length_list(List L)
{
	return L->Last + 1;
}
void print_list(List L)
{
	for (int i = 0; i < L->Last + 1; ++i)
	{
		printf("%d ", L->Data[i]);
	}
	printf("\n");
}

部分函数的测试代码

//测试代码的主函数
int main()
{
	List L = make_empty_list();

	for (int i = 0; i < 9; i++)   //设置为1,2,3,4,5,6,7,8,9
		insert_list(L, i + 1, i + 1);
	print_list(L);

	delete_list(L, 5); //删除第5个
	print_list(L);
	printf("线性表长度为:%d\n", length_list(L));

	insert_list(L, 1215, 5); //在第5个的前面插入1215
	print_list(L);

	printf("第7的值为:%d\n", find_kth_list(L, 7));
	int n = find_list(L, 1215);
	if (n)
	{
		printf("1215在第%d个位置\n", n);
	}
	else printf("1215不存在!\n");

	return 0;
}

运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值