数据结构:顺序表

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;
}
相关推荐
haoly198927 分钟前
数据结构和算法篇-线性查找优化-移至开头策略
数据结构·算法·移至开头策略
earthzhang20214 小时前
【1007】计算(a+b)×c的值
c语言·开发语言·数据结构·算法·青少年编程
冷徹 .8 小时前
2024ICPC区域赛香港站
数据结构·c++·算法
韧竹、9 小时前
数据结构之顺序表
c语言·数据结构
努力努力再努力wz13 小时前
【C++进阶系列】:万字详解智能指针(附模拟实现的源码)
java·linux·c语言·开发语言·数据结构·c++·python
敲代码的嘎仔14 小时前
JavaWeb零基础学习Day2——JS & Vue
java·开发语言·前端·javascript·数据结构·学习·算法
yacolex14 小时前
3.3_数据结构和算法复习-栈
数据结构·算法
cookqq15 小时前
MongoDB源码delete分析oplog:从删除链路到核心函数实现
数据结构·数据库·sql·mongodb·nosql
ʚ希希ɞ ྀ16 小时前
用队列实现栈---超全详细解
java·开发语言·数据结构
要一起看日出16 小时前
数据结构-----栈&队列
java·数据结构··队列