一:创建1.test.c负责测试 2.sqlist.h 负责声明函数,定义结构体,及包含头文件 3.sqlist.c 负责实现函数
二:代码过程
准备:test.c 与 sqlist.c包含头文件“sqlist.h”
test.c函数准备
#include "sqlist.h"
int main()
{
return 0;
}
1.在sqlist.中h结构体的创建
typedef int type;//可以一键更换数据类型
typedef struct sqlist
{
int* arr;
int size;//当前数据个数;
int capacity;//空间大小
}SL;//将结构体名字简化
此处的类型为:动态顺序表;优点可以自动开辟空间,防止内存不够引起空间泄露
2.
void Init(SL* ptr);//初始化函数
void Init(SL* ptr)
{
assert(ptr);//
ptr->arr = NULL;
ptr->capacity = ptr->size = 0;
}
需要头文件<assert.h>与<stdio.h>;
通过test函数可观察到成功与否;
3.
void Destroy(SL* ptr);//销毁
void Destroy(SL* ptr)//销毁
{
assert(ptr);
free(ptr->arr);
ptr->arr = NULL;
ptr->capacity = ptr->size = 0;
}
需要头文件<stdlib.h>
注意不要释放ptr,应释放ptr->arr;
4.
void Byeplace(SL* ptr);//申请空间函数
void Byeplace(SL*ptr)
{
assert(ptr);
if (ptr->capacity == ptr->size)
{
int newcapacity = ptr->capacity == 0 ? 4 : 2 * ptr->capacity;
type* new = (type*)realloc(ptr->arr, newcapacity * sizeof(type));
if (new == NULL)
{
perror("Addbehind()::realloc");
return;
}
ptr->arr = new;
ptr->capacity = newcapacity;
}
}
注意使用realloc而不是malloc.
5.
void Addbehind(SL* ptr,type x)//尾添
void Addbehind(SL* ptr,type x)//尾添
{
Byeplace(ptr);
ptr->arr[ptr->size++] = x;
}
6.void Print(SL* ptr)
void Print(SL* ptr)
{
assert(ptr);
for (int i = 0; i < ptr->size; i++)
{
printf("%d->", ptr->arr[i]);
}
printf("\n");
}
通过打印函数,很清楚插入是否成功。
7.
void Addhead(SL* ptr, type x)//头添
void Addhead(SL* ptr, type x)//头添
{
assert(ptr->arr&&ptr);
Byeplace(ptr);
for (int i = ptr->size; i > 0; i--)
{
ptr->arr[i] = ptr->arr[i - 1];
}
ptr->arr[0] = x;
ptr->size++;
}
8.void Popbehind(SL* ptr)//尾删
void Popbehind(SL* ptr)
{
assert(ptr->arr && ptr);
ptr->arr[ptr->size] = 0;
ptr->size--;
}
9.void Addposhead(SL* ptr, int pos, int x);//指定位置前插入
void Addposhead(SL* ptr, int pos, int x)//指定位置插入
{
assert(ptr&& ptr->arr);
assert(pos >= 0 && pos <= ptr->size);
for (int i = ptr->size; i > pos; i--)
{
ptr->arr[i] = ptr->arr[i - 1];
}
ptr->arr[pos] = x;
ptr->size++;
}
10.
void Poppos(SL* ptr, int pos)//删除指定位置数据
void Poppos(SL* ptr, int pos)//删除指定位置数据
{
assert(ptr);
assert(pos >= 0 && pos <= ptr->size);
for (int i = pos; i < ptr->size; i++)
{
ptr->arr[i] = ptr->arr[i + 1];
}
ptr->size--;
}
11.
int* Findpos(SL* ptr, type x);//查找
int Findpos(SL* ptr, type x)
{
for (int i = 0; i < ptr->size; i++)
{
if (ptr->arr[i] == x)
return i;
}
return -1;
}

2424

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



