数据结构:顺序表

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;
}
相关推荐
阿让啊27 分钟前
C语言中操作字节的某一位
c语言·开发语言·数据结构·单片机·算法
草莓啵啵~1 小时前
搜索二叉树-key的搜索模型
数据结构·c++
丶Darling.2 小时前
26考研 | 王道 | 数据结构 | 第八章 排序
数据结构·考研·排序算法
我也不曾来过13 小时前
list底层原理
数据结构·c++·list
mit6.8244 小时前
[贪心_7] 最优除法 | 跳跃游戏 II | 加油站
数据结构·算法·leetcode
keep intensify4 小时前
通讯录完善版本(详细讲解+源码)
c语言·开发语言·数据结构·算法
shix .4 小时前
2025年PTA天梯赛正式赛 | 算法竞赛,题目详解
数据结构·算法
egoist20235 小时前
【C++指南】告别C字符串陷阱:如何实现封装string?
开发语言·数据结构·c++·c++11·string·auto·深/浅拷贝
Gsen28195 小时前
AI大模型从0到1记录学习 数据结构和算法 day20
数据结构·学习·算法·生成对抗网络·目标跟踪·语言模型·知识图谱
一定要AK5 小时前
天梯——L1-110 这不是字符串题
数据结构·c++·算法