线性表线性储存头插,头删,尾插,尾删,特定位置增删,代码的实现
检查数据表,扩容一般是扩俩倍。
void SeqListCheckCapacity(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 fail\n");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
}
尾插,尾删
void SeqListPushBack(SL* ps, SLDataType x) //尾插
{
//如果没有空间或者空间不足,就扩容
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 fail\n");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->size] = x;
ps->size++;
}
void SeqListPopBack(SL* ps) //尾删
{
SeqListCheckCapacity(ps);
assert(ps->size > 0);
ps->size--;
}
头插,头删
插入数据后都要往后挪一项。
void SeqListPushFront(SL* ps, SLDataType x) //头插
{
SeqListCheckCapacity(ps);
//挪动数据
int end = ps->size - 1;
while (end >= 0)
{
ps->a[end + 1] = ps->a[end];
--end;
}
ps->a[0] = x;
ps->size++;
}
void SeqListPopFront(SL* ps) //头删
{
assert(ps->size > 0);
int begin = 1;
while (begin < ps->size)
{
ps->a[begin - 1] = ps->a[begin];
++begin;
}
ps->size--;
}
指定就位置插人删除数据
int SeqListFind(SL* ps, SLDataType x) //找到返回x位置下标,没有找到返回-1
{
int i = 0;
while (i < ps->size)
{
if (x == ps->a[i])
{
return i;
}
i++;
}
return -1;
}
void SeqListInsert(SL* ps, int pos, SLDataType x) //指定pos下标位置插入
{
SeqListCheckCapacity(ps);
int k = ps->size;
for (; k >pos; k--)
{
ps->a[k] = ps->a[k-1];
}
ps->a[pos] = x;
ps->size++;
}
线性储存与数组区别不大,在指定位置增删需要都要挪位置。