数据结构:顺序表

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;
}
相关推荐
散1121 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19431 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww1 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚1 天前
[数据结构] 排序
数据结构
睡不醒的kun1 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌1 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long1 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn1 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap
我星期八休息1 天前
深入理解跳表(Skip List):原理、实现与应用
开发语言·数据结构·人工智能·python·算法·list
和编程干到底1 天前
数据结构 栈和队列、树
数据结构·算法