顺序表的图解

其中a指向动态开辟数组;
size表示数据的数量;
capacity为数组的容量(满了就扩容);
其中,顺序表储存方式为连续储存。
顺序表的代码实现
一、h文件
头文件主要是用来定义顺序表+声明函数。
typedef int SeqListDatatype //定义元素的类型
#define INIT_CAPACITY 10 //定义数组的容量,方便后续扩容
typedef struct SeqList
{
SeqListDatatype* a;//定义指向数组的指针
int size;//创建数量变量
int capacity;//创建容量
}SL;//重命名为SL;
void SLInit(*p);//初始化顺序表
void CheckCapacity(*p);//动态检查顺序表,满了就扩容
void Destroy(*p);//销毁顺序表
void Print(*p);//打印顺序表
void SLinsert(*p,int pos,SeqListDatatype x);//顺序表插入数据
void SLErase(*p,int pos);//删除顺序表的某个数据
int SLFind(*p,SeqListDatatype x);//查找顺序表的某个元素,返回其位置下标。
二、.c文件
这里主要是实现顺序表函数的主体编译。
void SLInit(SL *p)
{
assert(p)//检查是否为空
p->a = (SeqListDatatype*)malloc(sizeof(SeqListDatatype)*INIT_CAPACITY);//为数组申请动态空间。
if(p->a == NULL)
{
perror("malloc fail");//申请失败就打印
}
p->size = 0;
p->capacity = 0;
}
void CheckCapacity(SL *p);
{
assert(*p);
if(p->size == p->capacity)
{
SeqListDatatype* tmp = (SeqListDatatype*)realloc(p->a,sizeof(SeqListDatatype)*(p->capacity*2)) ;
if(tmp == NULL)
{
perror("realloc fail");
return;
}
p->a = tmp;
p->capacity *= 2;
}
void Destroy(*p)
{
assert(p);
free(p->a);//释放空间
p->size = p->capacity = 0;//置0;
}
void Print(SL *p)
{
assert(p)
for(int i = 0;i<p->size;i++)
{
printf("%d ",p->a[i]);//遍历整个数组
}
printf("\n");
}
void SLinsert(SL *p,int pos,SeqListDatatype x)
{
assert(p);
assert(pos>=0&&pos<p->capacity);
CheckCapacity(p);
int end = p->size - pos - 1;//计算结束
while(end>=0)
{
p->a[end] = p->a[end+1];//修改元素
end -- ;
}
p->a[pos] = x;
p->size++;
}
void SLErase(SL *p,int pos)
{
assert(p);
assert(pos>=0&&pos<p->size);
int MoveBegin = pos+1;//定义位移的起点
while(MoveBgein<p->size)
{
p->a[MoveBegin-1] = p->a[MoveBegin];//从pos开始,后面的元素依次往前覆盖元素。
MoveBgein++;
}
p->size--;
}
int SLFind(SL *p,SeqListDatatype x)
{
assert(p);
for(int i = 0 ;i<size;i++)
{
if(p->a[i] == x)
{
return i;//返回下标
}
}
return -1;//返回失败
}
25万+

被折叠的 条评论
为什么被折叠?



