简介

虽说名叫顺序表,但其中的内容跟上篇的通讯录如出一辙,只不过略有不同的是这个顺序表定义的函数名遵循STL,而且只传入了整型的数据并没有像通讯录中的字符型那种。

1、定义一个SeqList结构体

结构体中需要存放的是指针a 当前有效数据size 容量 capacity

代码如下:
typedef int SLDateType;//这样可以简单的控制存入数据的类型 //定义一个SeqList 结构体 来存放 a size
capacity 变量 typedef struct SeqList { SLDateType* a; size_t size; size_t
capacity; // unsigned int }SeqList;
2、初始化

初始化刚才定义的指针和整型。

代码如下:
void SeqListInit(SeqList* ps) { ps->a = NULL; ps->size = 0; ps->capacity = 0; }
3、头插

头插,顾名思义在数据的头部插入一个数据。

代码如下:
//头插 void SeqListPushFront(SeqList* ps, SLDateType x) { assert(ps);
CheckCacpity(ps); for (int i = ps->size; i > 0; i--) { ps->a[i] = ps->a[i - 1];
} ps->a[0] = x; ps->size++; }
4、尾插

代码如下:
//尾插 void SeqListPushBack(SeqList* ps, SLDateType x) { assert(ps); //检查是否需要增容
CheckCacpity(ps); ps->a[ps->size] = x; ps->size++; }
5、头删
//头删 void SeqListPopFront(SeqList* ps) { assert(ps); for (int j = 0; j <
ps->size; j++) { ps->a[j] = ps->a[j + 1]; } ps->size--; }
6、尾删

代码如下:
//尾删 void SeqListPopBack(SeqList* ps) { assert(ps); ps->a[ps->size - 1] = 0;
ps->size--; }
7、查找

代码如下:
// 顺序表查找 int SeqListFind(SeqList* ps, SLDateType x) { assert(ps); for (int i =
0; i < ps->size; i++) { if (ps->a[i] == x) return i;//返回的是x的下标 } }
8、在任意位置插入

代码如下:
// 顺序表在pos位置插入x void SeqListInsert(SeqList* ps, int pos, SLDateType x) {
assert(ps); //int pos = SeqListFind(ps, x); for (int i = ps->size; i >= pos;
i--) { ps->a[i + 1] = ps->a[i]; } ps->a[pos] = x; ps->size++; }
9、删除任意位置的值

代码如下:
// 顺序表删除pos位置的值 void SeqListErase(SeqList* ps, size_t pos) { assert(ps); /*int
pos = SeqListFind(ps, pos);*/ for (int i = pos; i < ps->size; i++) { ps->a[i] =
ps->a[i + 1]; } ps->a[ps->size] = 0; ps->size--; }
10、打印
//将存入的数据进行打印 void SeqListPrint(SeqList* ps) { for (int i = 0; i < ps->size;
i++) { printf("%d ", ps->a[i]); } }
11、检查是否增容
//检查是否需要扩容 void CheckCacpity(SeqList* ps) { if (ps->size == ps->capacity) {
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2; ps->a = (SeqList *
)realloc(ps->a, newcapacity * sizeof(SeqList)); if(ps->a!=NULL) ps->capacity =
newcapacity; } }
12、释放空间
//将动态开辟的空间进行释放 void SeqListDestory(SeqList* ps) { free(ps->a); ps->a = NULL;
ps->size = 0; ps->capacity = 0; }
测试用例
#include"SeqList.h" void Test1() { SeqList con; SeqListInit(&con);
SeqListPushFront(&con, 1); SeqListPushFront(&con, 2); SeqListPushFront(&con,
3); SeqListPushFront(&con, 4); SeqListPushBack(&con, 1); SeqListPushBack(&con,
2); SeqListPushBack(&con, 3); SeqListPushBack(&con, 4); //SeqListInsert(&con,
1, 0); SeqListPopFront(&con); SeqListPopBack(&con); SeqListErase(&con,0);
SeqListPrint(&con); } int main() { Test1(); return 0; }

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信