Sequence_table.c功能函数的定义
1.头文件的声明
#include"Sequence_table.h"
2.初始化、销毁、打印函数的定义
//初始化顺序表
void SLInit(SL* ps)
{
ps->a = (SLDataType*)malloc(sizeof(SLDataType) * 4);
if (ps->a == NULL)
{
perror("malloc failed");
exit(-1);
//return;
}
ps->size = 0;
ps->capacity = 4;
}
//销毁顺序表
void SLDestroy(SL* ps)
{
free(ps->a);
ps->a = NULL;
ps->capacity = ps->size = 0;
}
//打印顺序表
void SLPrint(SL* ps)
{
for (int i = 0; i < ps->size; i++)
{
printf("%d ", ps->a[i]);
}
printf("\n");
}
3.扩容函数的定义
//扩容顺序表
void SLCheckCapacity(SL* ps)
{
if (ps->size == ps->capacity)
{
SLDataType* tmp = (SLDataType*)realloc(ps->a, ps->capacity * 2 * (sizeof(SLDataType)));
if (tmp == NULL)
{
perror("realloc failed");
exit(-1);
}
ps->a = tmp;
ps->capacity *= 2;
}
}
4.尾插尾删函数的定义
//尾插
void SLPushBack(SL* ps, SLDataType x)
{
SLCheckCapacity(ps);
ps->a[ps->size] = x;
ps->size++;
}
//尾删
void SLPopBack(SL* ps)
{
assert(ps->size > 0);
ps->size--;
}
5.头插头删函数的定义
//头插
void SLPushFront(SL* ps, SLDataType x)
{
SLCheckCapacity(ps);
// 挪动数据
int end = ps->size - 1;
while (end >= 0)
{
ps->a[end + 1] = ps->a[end];
--end;
}
ps->a[0] = x;
ps->size++;
}
//头删
void SLPopFront(SL* ps)
{
assert(ps->size > 0);
for (int i = 1; i <= ps->size - 1; i++) {
ps->a[i - 1] = ps->a[i];
}
ps->size--;
}
6.定位插入删除函数的定义
// 在pos位置插入x
void SLInsert(SL* ps, int pos, SLDataType x) {
SLCheckCapacity(ps);
int end = ps->size - 1;
for (int i = end; i >= pos-1; i--) {
ps->a[i + 1] = ps->a[i];
}
ps->a[pos-1] = x;
ps->size++;
}
// 删除pos位置的值
void SLErase(SL* ps, int pos) {
assert(ps->size > 0);
for (int i = pos-1; i < ps->size - 1; i++) {
ps->a[i] = ps->a[i+1];
}
ps->size--;