提示:文本为数据解构(一)后续补充文:
本文具体讲解顺序表的具体使用方法
提示:以下是本篇文
第一章 数据解构(一)
前言
系列文章目录
一、静态的使用方式
二、动态的使用方式
1.定义一个结构体
2.初始化
3.扩容
4.尾加
5.尾减
6.头加
7.头减
8.查找
9.删除pos位置的值
10.pos位置插入x
11.销毁
总结
提示:以下是本篇文章正文内容,下面案例可供参考
回顾上文说到
顺序表可以分为两种:
动态
使用动态来开辟的数组存储
静态
使用固定长度数组存储元素
代码如下(示例):
#define N 10//定义一个常量的宏
typedef int SLDataType;//从新定义int 的名称
typedef struct SeqList
{SLDataType a[N];//开辟一个固定大小的数组int size; //有效数据个数int capacity; //空间大小
}SL;
制作一个可以增,删,改,查,可扩容的数组
代码如下(示例):
typedef int SLDataType;//从新定义int 的名称typedef struct SeqList
{SLDataType* a;//开辟动态大小int size; //有效数据个数int capacity; //空间大小
}SL;
SLDataType* a;//开辟动态大小
int size; //有效数据个数int capacity; //空间大小
代码如下(示例):
void SListInit(SL* ps1)
{ps1->a = NULL;//把大小为空ps1->size = ps1->capacity = 0;//可用为0}
增容的目的是为了在输入数据时有可用空间
代码如下(示例):
void SLCheckcapicity(SL* ps1)
{if (ps1->capacity == ps1->size){//当空间大小为0时给开辟4个空间//如果有空间就把以前的空间乘2int newcapicity = ps1->capacity == 0 ? 4 : ps1->capacity * 2;SLDataType* tmp = (SLDataType*)realloc(ps1->a, newcapicity * sizeof(int*));if (tmp ==NULL){printf("扩容失败");exit(-1);}ps1->a = tmp;//扩容好后的空间给aps1->capacity = newcapicity;//把范围大小给capacity}
}
代码如下(示例):
void SLPushback(SL* ps1, SLDataType x)
{SLCheckcapicity(ps1);//先判度空间是否充足ps1->a[ps1->size] = x;ps1->size++;
}
代码如下(示例):
void SLPopback(SL* ps1)
{if (ps1->size > 0){ps1->a[ps1->size-1] = 0;ps1->size--;}}
代码如下(示例):
void SLPushFront(SL* ps1, SLDataType x)
{SLCheckcapicity(ps1);int end = ps1->size - 1;while (end >= 0){ps1->a[end + 1] = ps1->a[end];end--;} ps1->a[0] = x;ps1->size++;
}
代码如下(示例):
void SLPopFront(SL* ps1)
{int begin = 1;while (begin< ps1->size){ps1->a[begin-1] = ps1->a[begin];begin++;}ps1->size--;
}
代码如下(示例):
void SLFind(SL* ps1, SLDataType x)
{for (int i = 0; i < ps1->size; i++){if (ps1->a[i] == x) {return i;}}return -1;
}
代码如下(示例):
void SLErase(SL* ps1, int pos)
{if (pos <= ps1->size && pos >= 0){int begin = pos;while (begin size){ps1->a[begin-1] = ps1->a[begin];begin++;}ps1->size--;}
}
代码如下(示例):
void SLInsert(SL* ps1, int pos, SLDataType x)
{//这里的主要操作为选择的数不为下标而是数int y = pos == 0 ? pos : pos - 1;//因为顺表是连续的所以说不可以跳if (pos < ps1->size && pos >= 0){SLCheckcapicity(ps1);//判断是否需扩int end = ps1->size;while (end >= y){ps1->a[end + 1] = ps1->a[end];end--;}ps1->a[y] = x;ps1->size++;}
}
代码如下(示例):
void SLDestory(SL* ps1)
{int Destory = ps1->a[0];while (ps1->size>=Destory){ps1->size--;}
}
提示:这里对文章进行总结:
链表的问题是必须在内存中是连续存储,实践发现多次的使用,pos位置插入x可能会导致整个数组的顺序会有变化。
上一篇:2022——>2023