目录
顺序表:
- 概念部分:顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储,在数组上完成数据的增删查改。
- 顺序表一般分为:静态顺序表,动态顺序表
顺序表C语言实现:
首先你需要明确,你需要的基础功能应该有那些:
- 头插,头删
- 尾插,尾删
- 扩容
- 初始化
- 特定位置删除与插入
接下来开始实现:
在数据结构阶段应该将函数声明与实现分开来,养成好的代码习惯。
函数声明:
//初始化
void SLInit(SL* ps);
//检查空间
void SLcheckcapacity(SL*ps);
//尾插 尾删(o(1)) 头插 头删(0(n))
void SLPushBack(SL* ps, SLDatatype x);
void SLPopBack(SL* ps);
void SLPushFront(SL* ps, SLDatatype x);
void SLPopFront(SL* ps);
//特定位置插入 删除
void SLinsert(SL* ps, int pos, SLDatatype x);//pos 位置
void SLerase(SL* ps, int pos);
//输出函数
void SLprint(SL* ps);
首先需要创建一个结构体,我们需要有指向动态数组的指针,数组的空间容量,数组的有效元素。
typedef int SLDatatype;
typedef struct Seqlist {
SLDatatype* a;//指向动态数组指针
int size;//数据个数
int capacity;//容量-空间大小
}SL;
接下来,开始实现各部分功能:
初始化:
void SLInit(SL* ps) {
ps->a = NULL;
ps->size = ps->capacity = 0;
}
函数空间检查与扩容:
void SLcheckcapacity(SL* ps) {
if (ps->size == ps->capacity) {
int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
SLDatatype* tmp = (SLDatatype)realloc(ps->a, newCapacity * sizeof(SLDatatype));
if (tmp == NULL) {
printf("realloc fall\n");
exit(-1);
}
ps->a = tmp;
ps->capacity = newCapacity;
}
}
头插,头删,尾插,尾删:
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);
int begin = 1;
while (begin < ps->size) {
ps->a[begin - 1] = ps->a[begin];
begin++;
}
ps->size--;
}
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--;
}
特定位置的删除与插入:
void SLinsert(SL* ps, int pos, SLDatatype x) {
assert(ps&&pos>=0&&pos<ps->size);
SLcheckcapacity(ps);
int end = ps->size - 1;
while (end >=pos) {
ps->a[end + 1] = ps->a[end];
end--;
}
ps->a[pos] = x;
ps->size++;
}
void SLerase(SL* ps, int pos) {
assert(ps && pos >= 0 && pos < ps->size);
SLcheckcapacity(ps);
int begin = pos;
while (begin < ps->size - 1) {
ps->a[begin] = ps->a[begin + 1];
begin++;
}
ps->size--;
}