顺序表基本操作实现(超详细版)

 

 

一、函数的介绍

#define MAXSIZE 100
struct SList {
	int* data;
	int Length;

};

//将表中内容打印出来
void print(struct SList* L);

//顺序表的初始化
void InitList(struct SList* L);

//释放顺序表的内存(内存不在)
void DestoryList(struct SList* L);

//清空顺序表的内容(内存还在)
void ClearList(struct SList* L);

//获得顺序表的长度
int GetLength(struct SList* L);

//判断顺序表是否为空(是空返回1不是空返回0)
int IsEmpty(struct SList* L);

//将i位置上的内容返回给e
void GetElem(struct SList* L, int i, int* e);

//查找顺序表是否含有与e相同的内容
void LocateElem(struct SList* L, int e);

//向顺序表插入内容
void ListInsert(struct SList* L, int i, int e);

//向顺序表尾部插入内容
void EndInsert(struct SList* L, int n);

//将顺序表的i号位置删除
void ListDelete(struct SList* L, int i);

二、函数的实现

 

void InitList(struct SList* L)
{
	//申请内存 申请不成功返回NULL
	L->data = (int*)malloc(MAXSIZE);
	
	//判断内存是否申请成功
	if (L->data == NULL)
	{
		printf("内存分配失败!");
		exit(0);//退出程序
	}


	L->Length = 0;
}

void DestoryList(struct SList* L)
{
	//释放内存
	//如果data指向一个内存则释放内存(一定要注意释放后将指针设为空指针)
	if (L->data != NULL)
	{
		free(L->data);
		L->data = NULL;
		L->Length = 0;
	}
	else
	{
		printf("顺序表不存在,清空失败!!");
	}

}

void ClearList(struct SList* L)
{
	//在逻辑上清空,在物理上数据还存在.
	//下次写入新数据就可以将原有的数据覆盖了
	L->Length = 0;
}


int GetLength(struct SList* L)
{
	return L->Length;
}

int IsEmpty(struct SList* L)
{
	if (L->Length == 0)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

void GetElem(struct SList* L, int i, int* e)
{
	//判断i是否在合适的范围内
	if (i >= 0 && i < L->Length)
	{
		*e = L->data[i];
	}
	else
	{
		printf("输入的位置i不对!");
	}
}

void LocateElem(struct SList* L, int e)
{
	int i = 0;
	for (; i < L->Length; i++)
	{
		if (L->data[i] == e)
		{
			printf("查找成功! 在第%d位",i);
			return;
		}
	}


	printf("查找失败");

}

void ListInsert(struct SList* L, int i, int e)
{
	//判断插入位置i是否合法
	if (i<0 || i>L->Length + 1)
	{
		//插入位置不合法退出函数
		printf("插入位置不合法");
		return;
	}
	
	//判断储存空间是否满
	if (L->Length == MAXSIZE)
	{
		printf("内存已经满了!");
		return;
	}

	//将要插入的位置后面的数据挪到后面一位
	for (int j = L->Length - 1; j != i - 1; j--)
	{
		printf("%d\n", j);
		L->data[j + 1] = L->data[j];
	}

	L->data[i] = e;
	
	L->Length++;
	
}

void print(struct SList* L)
{
	if (L->Length == 0)
	{
		printf("无元素");
	}
	for (int i = 0; i < L->Length; i++)
	{
		printf("第%d位 = %d ", i, L->data[i]);
	}
}

void ListDelete(struct SList* L, int i)
{
	//判断i是否合法
	if (i<0 || i>L->Length - 1)
	{
		printf("i不合法");
		return;
	}

	for (int j = i; j < L->Length - 1; j++)
	{
		L->data[j] = L->data[j + 1];
	}
	L->Length--;
}

void EndInsert(struct SList* L,int n)
{
	L->data[L->Length] = n;
	L->Length++;
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sinnp

谢谢宝子的打赏,mua!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值