第二章、线性表

线性表

2.1、定义

线性表:是最常用的一种数据结构,一个线性表是n个数据元素的有限序列。
数据项:一个数据元素可以由若干个数据项组成。例如用户表中的 用户名
记录:数据元素称为记录
文件:含有大量记录的线性表又称为文件。
抽象数据类型线性表的定义如下:
在这里插入图片描述

2.2 线性表的顺序表示和实现

顺序表示:是指用一组地址连续的存储单元依次存储线性表的数据元素。
假定线性表的每个元素需要占用l个存储单元,并以所占的第一个单元的存储地址作为数据元素的存储位置。则线性表中第i+1个数据元素的位置为
LOC(ai+1) = LOC(ai)+l
线性表的第i个元素ai的存储位置为:
LOC(ai) = LOC(ai) + (i-1)*l
在这里插入图片描述

2.2.1、公共常量和类型定义

通用常量定义

//函数结果状态代码
constexpr auto TRUE = 1;
constexpr auto FALSE = 0;
constexpr auto OK = 1;
constexpr auto ERROR = 0;
constexpr auto INFEASIBLE = -1;
//Status是函数的类型,其值是函数结果状态码
typedef int			Status;

c结构图定义

#define LIST_INIT_SIZE	100	//线性表存储空间的初始化配量
#define LISTINCREMENT	10	//线性表存储空间的分配增量

typedef int	 ElemType;		//当前方法中使用的元素

typedef struct{
ElemType *elem;		//存储空间地址
int	length;			//当前长度
int listsize;		//当前分配的存储容量
}SqList;

elem:指示线性表的基地址
length:指示线性表的当前长度

  • 初始化方法
Status InitList(SqList &sqList)
{
	sqList.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
	if (!sqList.elem) {					//存储分配失败
		exit(OVERFLOW);	
	}
	sqList.length = 0;					//空表长度为0
	sqList.listsize = LIST_INIT_SIZE;	//初始存储容量
	return OK;
} //InitList
  • 插入元素
Status ListInsert(SqList &sqList,int i, ElemType e)
{
	//在顺序线性表sqList中第i个位置之前插入新的元素e,
	if (i<1 || i>sqList.length + 1) 
	{
		return ERROR;
	}
	//当前存储空间已满,增加分配
	if (sqList.length >= sqList.listsize)
	{
		ElemType* newbase = (ElemType*)realloc(sqList.elem, (sqList.listsize + LISTINCREMENT) * sizeof(ElemType));
		if (!newbase)
		{
			exit(OVERFLOW);					//分配空间失败
		}	
		sqList.elem = newbase;				//新基址
		sqList.listsize += LISTINCREMENT;	//增加存储容量
	}
	ElemType* elem = &(sqList.elem[i - 1]);
 	for (ElemType* p = &(sqList.elem[sqList.length - 1]); p >= elem; --p)
	{
		*(p + 1) = *p;
	}
	*elem = e;
	++sqList.length;
	return OK;
}
  • 删除元素
//在顺序线性表sqList中删除第i个元素,并用e返回其值
Status ListDelete(SqList &sqList, int i, ElemType &e)
{
	if (i < 1 || (i > sqList.length))
	{
		return ERROR;							//i值不合法
	}
	ElemType *elem = &(sqList.elem[i - 1]);		//elem为被删除的元素位置
	e = *elem;
	ElemType *tail = sqList.elem + sqList.length - 1; //被删除元素的值赋给e
	for (++elem; elem <= tail; elem++)			//被删除元素之后的元素左移
	{
		*(elem - 1) = *elem;
	}
	--sqList.length;							//表长减1
	return OK;
}
  • 遍历方法
void ListShow(SqList sqList)
{
	int length = sqList.length;
	int listsize = sqList.listsize;
	cout << "length:" << length << "\tlistsize:" << listsize << endl;
	for (int i = 0; i < length; i++)
	{
		cout << sqList.elem[i] <<"\t";
	}
	cout << endl;
}
  • 测试方法
int main()
{
	SqList sqList;
	InitList(sqList);
	for (int i = 1; i <= 100; i++)
	{
		ListInsert(sqList, i, i);
	}
	ListInsert(sqList, 10, 11);
	ListShow(sqList);
	system("pause");
	return OK;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值