数据结构:顺序表

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;
}
相关推荐
小十一再加一6 分钟前
【数据结构初阶】单链表
数据结构
ZIM学编程2 小时前
「学长有话说」作为一个大三学长,我想对大一计算机专业学生说这些!
java·c语言·数据结构·c++·python·学习·php
子枫秋月4 小时前
单链表实现全解析
c语言·数据结构·c++
刀法自然4 小时前
栈实现表达式求值
数据结构·算法·图论
Yupureki5 小时前
从零开始的C++学习生活 19:C++复习课(5.4w字全解析)
c语言·数据结构·c++·学习·1024程序员节
ゞ 正在缓冲99%…6 小时前
leetcode1312.让字符串成为回文串的最少插入次数
数据结构·算法·leetcode·动态规划·记忆化搜索
laocooon5238578867 小时前
寻找使a×b=c成立的最小进制数(2-16进制)
数据结构·算法
一匹电信狗10 小时前
【牛客CM11】链表分割
c语言·开发语言·数据结构·c++·算法·leetcode·stl
不染尘.11 小时前
图的邻接矩阵实现以及遍历
开发语言·数据结构·vscode·算法·深度优先
xiaoye-duck11 小时前
数据结构之栈和队列-栈
数据结构