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

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

前言:

顺序表格的特点:

  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;
}
相关推荐
@我漫长的孤独流浪15 分钟前
最短路与拓扑(2)
数据结构·c++·算法
٩( 'ω' )و26038 分钟前
哈希表的实现01
数据结构·c++·哈希算法·散列表
YuforiaCode1 小时前
LeetCode 热题 100 35.搜索插入位置
数据结构·算法·leetcode
水水沝淼㵘3 小时前
嵌入式开发学习日志(数据结构--单链表)Day20
c语言·开发语言·数据结构·学习·算法
学习中的码虫5 小时前
数据结构中的高级排序算法
数据结构·算法·排序算法
闪电麦坤957 小时前
数据结构:树(Tree)
数据结构
Musennn7 小时前
102. 二叉树的层序遍历详解:队列操作与层级分组的核心逻辑
java·数据结构·算法·leetcode
学习中的码虫8 小时前
c 中的哈希表
数据结构·哈希算法·散列表
ll77881117 小时前
C++学习之路,从0到精通的征途:继承
开发语言·数据结构·c++·学习·算法
Akiiiira18 小时前
【数据结构】栈
数据结构