数据结构——(顺序表)

一、顺序表

1.概念

2、动态顺序表:使用动态开辟的数组存储

二、顺序表的实现

1、接口的实现

(1)创建

(2)初始化

(3)扩容

(4)尾插

(5)尾删

(6)头插

(7)头删

(8)插入任意位置

(9)删除任意位置

(10)查找

(11)打印

三、完整代码

一、顺序表
1.概念
顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数据的增删查改。
动态顺序表:使用动态开辟的数组存储
在这里插入图片描述

二、顺序表的实现
1、接口的实现
在这里插入图片描述
(1)创建
为了养成模块化好习惯,我们尽量把代码分开来写。首先打开 VS2019,在解决方案资源管理器中的 “头文件” 文件夹中创建 SeqList.h 用来存放头文件。在 “源文件” 文件夹中创建 SeqList.c 用来实现函数,源.c 用来测试我们的顺序表:
(2)初始化
在这里插入图片描述
(3)扩容
在这里插入图片描述
(4)尾插
在这里插入图片描述
(5)尾删
在这里插入图片描述
(6)头插
在这里插入图片描述
(7)头删
在这里插入图片描述
(8)插入任意位置
在这里插入图片描述
(9)删除任意位置
在这里插入图片描述
(10)查找
在这里插入图片描述

(11)打印
在这里插入图片描述
三、完整代码

#include"SeqList.h"
void SLInit(SL *ps)
{
	ps->arr =(int*)malloc(sizeof(int)*INIT_capacity);
	if (ps->arr == NULL)
	{
		perror("malloc fail");
		return;
	}
	ps->s = 0;
	ps->capacity = INIT_capacity;
}
void SLDestroy(SL* ps)
{
	free(ps->arr);
	ps->arr = NULL;
	ps->s = 0;
	ps->capacity = 0;
}
void SLprint(SL* ps)
{
	for (int i = 0; i < ps->s; i++)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("\n");
}
void SLPushBack(SL* ps, int x)
{
	SLcheckcapacity(ps);
	ps->arr[ps->s++] = x;
}
void SLPopBack(SL* ps)
{
	if (ps->s == 0)
		return;
	ps->s--;
}
void SLPushFront(SL* ps, int x)
{
	int end = ps->s - 1;
	while (end >= 0)
	{
		ps->arr[end + 1] = ps->arr[end];
		end--;
	}
	ps->arr[0] = x;
	ps->s++;
}
void SLcheckcapacity(SL* ps)
{
	if (ps->s == ps->capacity)
	{
		int* tmp = (int*)realloc(ps->arr, sizeof(int) * ps->capacity * 2);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->arr = tmp;
		ps->capacity *= 2;
	}
}
void SLPopFront(SL* ps)
{
	assert(ps->s > 0);
	int begin = 1;
	while (begin < ps->s)
	{
		ps->arr[begin - 1] = ps->arr[begin];
		begin++;
	}
	ps->s--;
}
void SLInsert(SL* ps, int pos, int x)
{
	assert(ps);
	assert(pos >=0&&pos<=ps->s);
	SLcheckcapacity(ps);
	int end = ps->s - 1;
	while (end >= pos)
	{
		ps->arr[end + 1] = ps->arr[end];
		end--;
	}
	ps->arr[pos] = x;
	ps->s++;
}
void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->s);
	int begin = pos+1;
	while (begin < ps->s)
	{
		ps->arr[begin - 1] = ps->arr[begin];
		begin++;
	}
	ps->s--;
}
void SLFind(SL* ps, int x)
{
	assert(ps);
	for (int i = 0; i < ps->s; i++)
	{
		if (ps->arr[i] == x)
		{
			return i;
		}
		return -1;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值