数据结构:顺序表

1.顺序表的概念

顺序表是用一段 物理地址连续 的存储单元依次存储数据元素的线性结构,一般情况下采用数组存
储。在数组上完成数据的增删查改。

2.接口实现

2.1初始化

cpp 复制代码
void SLInit(SL* psl)
{
	assert(psl);
	psl->a = (SeqListData*)malloc(sizeof(SeqListData)*4);
	if (NULL == psl->a)
	{
		perror("malloc");
		return;
	}
	psl->capacity = 4;
	psl->size = 0;
}

2.2销毁

cpp 复制代码
void SLDestroy(SL* psl)
{
	assert(psl);
	free(psl->a);
	psl->a = NULL;
	psl->capacity = 0;
	psl->size = 0;
}

2.3顺序表打印

cpp 复制代码
void SLPrint(SL* psl)
{
	assert(psl);

	for (int i = 0; i < psl->size; i++)
	{
		printf("%d ",psl->a[i]);
	}
}

2.4增加数据

2.4.1检查容量

cpp 复制代码
void ChackCapacity(SL* psl)
{
	assert(psl);

	if (psl->size == psl->capacity)
	{
		SeqListData* tmp = (SeqListData*)realloc(psl->a, sizeof(SeqListData) * psl->capacity * 2);
		if (NULL == tmp)
		{
			perror("realloc fail");
			return;
		}
		psl->a = tmp;
		psl->capacity *= 2;
	}
}

在增加数据之前,需要检查是否有足够的容量。不够就扩容。

2.4.2头插

cpp 复制代码
void SLPushFront(SL* psl, SeqListData x)
{
	assert(psl);

	ChackCapacity(psl);
	int end = psl->size - 1;
	while (end >= 0)
	{
		psl->a[end + 1] = psl->a[end];
		end--;
	}
	psl->a[0] = x;
	psl->size++;
}

2.4.3尾插

cpp 复制代码
void SLPushBack(SL* psl, SeqListData x)
{
	assert(psl);

	ChackCapacity(psl);
	psl->a[psl->size++] = x;
}

2.4.4在pos位置增加数据

cpp 复制代码
void SLInsert(SL* psl, int pos, SeqListData x)
{
	assert(psl);
	assert(0<=pos && pos<= psl->size);
	ChackCapacity(psl);
	int end = psl->size - 1;
	while (end >= pos)
	{
		psl->a[end+1] = psl->a[end];
		end--;
	}
	psl->a[pos] = x;
	psl->size++;
}

前面的头插和尾插可以复用这段代码。

2.5删除数据

2.5.1头删

cpp 复制代码
void SLPopFront(SL* psl)
{
	assert(psl);
	assert(psl->size > 0);
	int start = 0;
	while(start < psl->size - 1)
	{
		psl->a[start] = psl->a[start+1];
		++start;
	}
	psl->size--;
}

2.5.2尾删

cpp 复制代码
void SLPopBack(SL* psl)
{
	assert(psl);
	assert(psl->size > 0);
	psl->size--;
}

2.5.3在pos位置删除数据

cpp 复制代码
void SLErase(SL* psl, int pos)
{
	assert(psl);
	assert(0<=pos && pos<psl->size);
	int start = pos + 1;
	while (start < psl->size)
	{
		psl->a[start-1] = psl->a[start];
		start++;
	}
	psl->size--;
}

头删和尾删可以复用这段代码。

2.6查找数据

cpp 复制代码
int SLFind(SL* psl, SeqListData x)
{
	assert(psl);

	for (int i = 0; i < psl->size; i++)
	{
		if (psl->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}

2.7修改数据

cpp 复制代码
void SLModify(SL* psl, SeqListData x, int pos)
{
	assert(psl);

	psl->a[pos] = x;
}
相关推荐
Rain_is_bad1 小时前
初识c语言————排序方法
c语言·开发语言·数据结构
一支闲人2 小时前
C语言相关简单数据结构:顺序表
c语言·数据结构·基础知识·适用新手小白
霖003 小时前
FPGA的PS基础1
数据结构·人工智能·windows·git·算法·fpga开发
数据智能老司机5 小时前
图算法趣味学——桥和割点
数据结构·算法·云计算
John.Lewis6 小时前
数据结构初阶(11)排序的概念与运用
c语言·数据结构·排序算法
FPGA7 小时前
曼彻斯特编解码:数字世界的“摩斯密码”与FPGA高效实现
数据结构
数据智能老司机7 小时前
图算法趣味学——图遍历
数据结构·算法·云计算
Gu_shiwww8 小时前
数据结构3线性表——单链表(C)
c语言·开发语言·数据结构
科大饭桶9 小时前
Linux系统编程Day13 -- 程序地址空间(进阶)
linux·运维·c语言·数据结构·c++
C_Liu_10 小时前
C语言:队列的实现和剖析
c语言·开发语言·数据结构