顺序表以及实现(结构篇)

顺序表是一种线性表的存储结构,它使用一组地址连续的存储单元依次存储线性表的数据元素。在顺序表中,逻辑上相邻的元素在物理存储上也相邻,通常采用数组来实现这种存储方式。

前言:

顺序表格的特点:

  1. 随机访问:可以通过首地址和元素序号在常数时间内找到指定的元素。
  2. 存储密度高:由于每个结点只存储数据元素,没有额外开销,因此存储密度较高。
  3. 物理位置相邻:物理位置和逻辑位置一致,保持相邻,但这也意味着插入和删除操作可能涉及到大量元素的移动。

顺序表简单介绍:

  • 顺序表主要分为动态和静态,由于静态局限性,在这主要实现动态顺序表。
  • 动态顺序表主要运用malloc()和realloc()函数对内存进行动态开辟。
  • 动态顺序表主要涉及初始化,销毁,增容,插入,删除,查找。

准备工作;

复制代码
#include <stdlib.h>
#include <assert.h>

typedef  int  SLDataType;

#define Initcapacity  3

typedef struct SeqList
{
	SLDataType* a;
	int size;
	int capacity;
}SL;

定义:

结构体 SL;重定义int类型;包含所需要的头文件

一、初 始 化(malloc)

二、销 毁 (free)

复制代码
//空间销毁
void SLDestory(SL* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

三、增 容(realloc)

复制代码
//检查容量并增加
void CheckCapacity(SL* ps)
{
	if (ps->size == ps->capacity)
	{
		SLDataType* tmp = (SLDataType*)realloc(ps->a, sizeof(SLDataType) * ps->capacity * 2);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->capacity *= 2;
		ps->a = tmp;
	}
}

四、插入

4.1 头 插

复制代码
//头插
void SeqListPushFront(SL* ps, SLDataType x)
{
	assert(ps);
	CheckCapacity(ps);
	int end = ps->size - 1;
	if (ps->size > 0)
	{
		while (end >= 0)
		{
			ps->a[end + 1] = ps->a[end];
			end--;
		}
	}
	ps->a[0] = x;
	ps->size++;
}

4.2 尾 插

复制代码
void SeqListPushBack(SL* ps, SLDataType x)
{
	assert(ps);

	CheckCapacity(ps);
	
	ps->a[ps->size] = x;
	ps->size++;
}

4.3 指 定 位 置 插 入

复制代码
// insert 元素
void SeqListInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size - 1);
	CheckCapacity(ps);
	int end = ps->size - 1;
	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end + 1];
		end--;
	}
	ps->a[pos] = x;
}

五、删除

5.1 头 删

复制代码
// 头删
void SeqListPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);
	int begin = 1;
	while (begin < ps->size)
	{
		ps->a[begin - 1] = ps->a[begin];
		begin++;
	}
	ps->size--;

}

5.3 尾 删

复制代码
//尾删
void SeqListPopBack(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);
	ps->size--;

}

5.3 指 定 位 置 删 除

复制代码
//指定位置删元素
void SeqListErase(SL* ps, int pos)
{
	assert(ps);
	assert(ps >= 0 && pos < ps->size);
	int begin = pos - 1;
	while (begin < ps->size - 1)
	{
		ps->a[begin] = ps->a[begin + 1];
		begin++;
	}
	ps->size--;
}

六、查 找

复制代码
//暴力查找
int SeqListFind(SL* ps, SLDataType x)
{
	assert(ps);
	int pos = 0;
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			pos = i;
			break;
		}
	}

	return pos;
}
相关推荐
要下雨了吗4 分钟前
指针数组 vs 数组指针
c语言·数据结构·c++·算法·visual studio
武装头脑ing39 分钟前
递增子序列
数据结构·算法
sml259(劳改版)1 小时前
(PTA) L2-011-L2-015
数据结构·算法
风铃儿~4 小时前
Redis过期key处理、内存淘汰策略与缓存一致性策略实践方案
java·数据结构·redis·微服务
大龄门外汉4 小时前
数据结构之栈和队列
c语言·数据结构·学习·改行学it
朝九晚五ฺ4 小时前
【算法学习】链表篇:链表的常用技巧和操作总结
数据结构·学习·算法·链表
俄城杜小帅5 小时前
数据结构刷题之贪心算法
数据结构·算法·贪心算法
什码情况5 小时前
整数编码 - 华为OD统一考试(A卷、C++)
数据结构·c++·算法·华为od
int型码农5 小时前
数据结构第六章(一) -图
c语言·数据结构·算法
泽02027 小时前
括号匹配问题--栈
数据结构