源码如下:
头文件:Seqlist.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#define Init_Capicity 4
//顺序表SeqList 存放的数据类型:SLtypedate
typedef int SLtypedate;
typedef struct SeqList
{
SLtypedate* arr; //所要开辟的空间的地址
int size; //有效数据个数
int capicity; //已经开辟的容量
}SL;
//初始化,删除
void SLInit(SL* ps);
void SLDestory(SL* ps);
//头插,头删
void PushFront(SL* ps, SLtypedate x);
void PoPFront(SL* ps);
//尾插,尾删
void PushBack(SL* ps, SLtypedate x);
void PoPBack(SL* ps);
//间插
void SLinsert(SL* ps, SLtypedate x, int pos);
//剪删
void SLErase(SL* ps, int pos);
//检查扩容
void SLCheckCapicity(SL* ps);
SeqList.c 源文件
#include"SeqListr.h"
//初始化
void SLInit(SL* ps)
{
assert(ps);
ps->arr = (SLtypedate*)malloc(sizeof(SLtypedate) * Init_Capicity);
//检查
if (ps->arr == NULL)
{
perror("malloc fail:");
return;
}
ps->capicity = Init_Capicity;
ps->size = 0;
}
//结构体数据的销毁
void SLDestory(SL* ps)
{
assert(ps);
ps->capicity = ps->size = 0;
free(ps);
ps = NULL;
}
//内存检查
void SLCheckCapicity(SL* ps)
{
assert(ps);
//扩容 void* realloc (void* ptr, size_t size);
if (ps->size == ps->capicity)
{
SLtypedate* tmp = (SLtypedate*)realloc(ps->arr, sizeof(SLtypedate) * ps->capicity * 2);
if (tmp == NULL)
{
perror("PushBack realloc");
return;
}
//检查没问题将tmp赋值给数组首地址arr
ps->arr = tmp;
ps->capicity *= 2;
}
}
//尾插的实现
void PushBack(SL* ps, SLtypedate x)
{
assert(ps);
//扩容
SLCheckCapicity(ps);
ps->arr[ps->size++] = x;
}
//尾删的实现
void PoPBack(SL* ps)
{
assert(ps);
//不能一直删除,否则size会变成负数
assert(ps->size > 0);
ps->size--;
}
//头插的实现
void PushFront(SL* ps, SLtypedate x)
{
assert(ps);
//扩容 void* realloc (void* ptr, size_t size);
SLCheckCapicity(ps);
//头插后移
SLtypedate end = ps->size;
while (end != 0)
{
ps->arr[end] = ps->arr[end - 1];
end--;
}
//头插
ps->arr[0] = x;
ps->size++;
}
//头删的实现
void PoPFront(SL* ps)
{
SLtypedate i = 0;
assert(ps->size > 0);
while (i+1!=ps->size)
{
ps->arr[i] = ps->arr[i + 1];
}
ps->size--;
}
//间插的实现
void SLinsert(SL* ps, SLtypedate x, int pos)
{
assert(ps);
assert(pos > 0 && pos <= ps->size);
SLCheckCapicity(ps);
int i = ps->size;
while (i>pos)
{
ps->arr[i] = ps->arr[i - 1];
i--;
}
ps->arr[pos] = x;
ps->size++;
}
//间删的实现
void SLErase(SL* ps, int pos)
{
//空指针,pos范围
assert(ps);
assert(pos >= 0 && pos < ps->size);
//左移
int i = pos + 1;
while (i<ps->size)
{
ps->arr[i - 1] = ps->arr[i];
i++;
}
ps->size-1;
}
函数测试文件 test.c ,mian函数中可以根据函数来进行测试
#include"SeqListr.h"
SL s1;
int main()
{
return 0;
}