顺序表本质:数组
顺序表的定义
typedef int SLDatatype;
typedef struct Seqlist
{
SLDatatype* a;
int size;//存储的有效数据的个数
int capacity;//容量
}SL;
顺序表的增删改查
顺序表的初始化
void SLInit(SL* psl)//初始化
{
/*psl->a = NULL;
psl->size = 0;
psl->capacity = 0;*/
psl->a = (SLDatatype*)malloc(sizeof(SLDatatype) * 4);
if (psl->a == NULL)
{
perror("malloc fail");
return;
}
psl->capacity = 4;
psl->size = 0;
}
顺序表的销毁
void SLDestory(SL* psl)//销毁
{
free(psl->a);
psl->a = NULL;
psl->capacity = 0;
psl->size = 0;
}
顺序表的插入
void SLCheckcapacity(SL* psl)//检查容量大小
{
if (psl->capacity == psl->size)
{
SLDatatype* tmp = (SLDatatype*)realloc(psl->a, sizeof(SLDatatype) * psl->capacity * 2);
if (tmp == NULL)
{
perror("realloc fail");
return;
}
psl->a = tmp;
psl->capacity *= 2;
}
}
void SLPushBack(SL* psl, SLDatatype x)//尾插
{
//判断容量
SLCheckcapacity(psl);
psl->a[psl->size] = x;
psl->size++;
}
void SLPushFront(SL* psl, SLDatatype x)//头插
{
SLCheckcapacity(psl);
int end = psl->size - 1;
while (end >= 0)
{
psl->a[end + 1] = psl->a[end];
--end;
}
psl->a[0] = x;
psl->size++;
}
void SLInsert(SL* psl, int pos, SLDatatype x)//任意位置插入
{
assert(pos >= 0 && pos <= psl->size);
//判容量
SLCheckcapacity(psl);
//先挪数据(从后往前挪)
int end = psl->size - 1;
while (end >= pos)
{
psl->a[end + 1] = psl->a[end];
--end;
}
//后插入
psl->a[pos] = x;
psl->size++;
}
顺序表的删除
void SLPopFront(SL* psl)//头删
{
assert(psl->size > 0);
int start = 0;
while (start < psl->size)
{
psl->a[start] = psl->a[start + 1];
++start;
}
psl->size--;
}
void SLPopBack(SL* psl) //尾删
{
//判断是否为空
assert(psl->size>0);
psl->size--;
}
void SLErase(SL* psl, int pos)//任意位置删除
{
assert(pos >= 0 && pos <= psl->size);
int end = pos+1;
while (end < psl->size)
{
psl->a[end-1] = psl->a[end];
end++;
}
psl->size--;
}
顺序表的查找,修改和打印
void SLPrint(SL* psl)//打印
{
for (int i = 0;i < psl->size;i++)
{
printf("%d ", psl->a[i]);
}
}
int SLFind(SL* psl, SLDatatype x)//查找
{
for (int i = 0;i < psl->size;i++)
{
if (psl->a[i] == x)
{
return i;
}
}
return -1;
}
void SLModify(SL* psl, int pos, SLDatatype x)//修改
{
assert(pos >= 0 && pos <= psl->size);
psl->a[pos] = x;
}