目录
1.线性表
2.顺序表
1.线性表
线性表是一种常见的数据结构,它由一组按照顺序存储的元素组成。线性表中的元素之间存在一对一的关系,即每个元素都有唯一的直接前驱和直接后继(除了第一个和最后一个元素)。常见的线性表:顺序表、链表、栈、队列、字符串等等。
线性表在逻辑上是线性结构,也就说是连续的一条直线。但是在物理结构上并不一定是连续的, 线性表在物理上存储时,通常以数组和链式结构的形式存储。
2.顺序表
2.1概念及结构
顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存 储。在数组上完成数据的增删查改

顺序表一般可分为
1.静态顺序表:使用定长数组存储元素
2.动态顺序表:使用动态开辟的数组存储
2.2接口实现
typedef int SLDataType;
typedef struct SeqList
{
SLDataType* a;
int size;
int capacity;
}SL;
void SLInit(SL* ps);//初始化顺序表
void SLDestory(SL* ps);//销毁顺序表
void SLPrint(SL* ps);
void SLCheakCapacity(SL* ps);
void SLPushBack(SL* ps,SLDataType x); //尾插
void SLPopBack(SL* ps); //尾删
void SLPushFront(SL* ps, SLDataType x);//头插
void SLPopFront(SL* ps);//头删
//在pos位置插入和删除
void SLInsert(SL* ps, int pos, SLDataType x);
void SLErase(SL* ps, int pos);
void SLModify(SL* ps, int pos, SLDataType x);
void SLInit(SL* ps)
{
assert(ps);
ps->a = (SLDataType*)malloc(sizeof(SLDataType) * 4);
if (ps->a == NULL)
{
perror("malloc fail\n");
exit(-1);
}
ps->size = 0;
ps->capacity = 4;
}
void SLDestory(SL* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->size = ps->capacity = 0;
}
void SLPrint(SL* ps)
{
assert(ps);
for (int i = 0; i < ps->size; i++)
{
printf("%d ", ps->a[i]);
}
printf("\n");
}
void SLCheakCapacity(SL* ps)
{
assert(ps);
//满了扩容
if (ps->size == ps->capacity)
{
SLDataType* tmp = (SLDataType*)realloc(ps->a, ps->capacity * 2 * sizeof(SLDataType));
if (tmp == NULL)
{
perror("realloc fail\n");
exit(-1);
}
ps->a = tmp;
ps->capacity *= 2;
}
}
void SLPushBack(SL* ps, SLDataType x) //尾插
{
//满了扩容
assert(ps);
SLCheakCapacity(ps);
ps->a[ps->size] = x;
ps->size++;
}
void SLPopBack(SL* ps) //尾删
{
assert(ps);
assert(ps->a);
ps->size--;
}
void SLPushFront(SL* ps, SLDataType x)//头插
{
assert(ps);
SLCheakCapacity(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);
assert(ps->a);
int begin = 1;
while (begin < ps->size )
{
ps->a[begin - 1] = ps->a[begin];
begin++;
}
ps->size--;
}
void SLInsert(SL* ps, int pos, SLDataType x)
{
assert(ps);
assert(pos >= 0 && pos <= ps->size);
SLCheakCapacity(ps);
int end = ps->size - 1;
while (pos <= end)
{
ps->a[end + 1] = ps->a[end];
end--;
}
ps->a[pos] = x;
ps->size++;
}
void SLErase(SL* ps, int pos)
{
assert(ps);
assert(pos >= 0 && pos < ps->size);
int begin = pos + 1;
while (begin < ps->size)
{
ps->a[begin - 1] = ps->a[begin];
begin++;
}
ps->size--;
}
void SLModify(SL* ps, int pos, SLDataType x)
{
assert(ps);
assert(pos >= 0 && pos < ps->size);
ps->a[pos] = x;
}