顺序表的描述及实现
程序员文章站
2024-03-20 14:37:40
...
顺序表的概念:
顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数据的增删查改。
顺序表就是数组,但是在数组的基础上,它还要求数据是从头开始并且连续存储的,不能跳跃间隔
一、顺序表结构
typedef int SQLDataType;
typedef struct SeqList
{
SQLDataType* a[];
int size; //顺序表储存数据的当前大小
int capacity; //顺序表能够储存数据的最大容量
}ST;
二、接口函数
//检验顺序表是否满了
void SeqListCheck(SQList* plist);
//打印
void SeqListPrint(SQList* plist);
//初始化
void SeqListInit(SQList* plist);
//销毁
void SeqListDestroy(SQList* plist);
//尾插
void SeqListPushBack(SQList* plist,SQLDataType x);
//尾删
void SeqListPopBack(SQList* plist);
//头插
void SeqListPushFront(SQList* plist,SQLDataType x);
//头删
void SeqListPopFront(SQList* plist);
//找X (找到了返回pos坐标,找不到返回-1)
int SeqListFrind(SQList* plist, SQLDataType x);
//在pos位置插入
void SeqListInsert(SQList* plist, int pos, SQLDataType x);
//删出pos处值
void SeqListErase(SQList* plist, int pos);
3.代码实现
void SeqListPrint(SQList* plist)
{
assert(plist);
for (int i = 0; i < plist->size; i++)
{
printf("%d ", plist->a[i]);
}
printf("\n");
}
void SeqListInit(SQList* plist)
{
assert(plist);
plist->a = NULL;
plist->capacity = plist->size = 0;
}
void SeqListDestroy(SQList* plist)
{
free(plist->a);
plist->a = NULL;
plist->capacity = plist->size = 0;
}
void SeqListCheck(SQList* plist)
{
assert(plist);
//如果满了 就扩容
if (plist->capacity == plist->size)
{
int newcapacity = plist->capacity == 0 ? 4 : plist->capacity * 2;
SQLDataType* tmp = (SQLDataType*)realloc(plist->a, sizeof(SQLDataType) * newcapacity);
//扩容失败
if (tmp == NULL)
{
printf("realloc Fail");
exit(-1);
}
plist->a = tmp;
plist->capacity = newcapacity;
}
}
void SeqListPushBack(SQList* plist, SQLDataType x)
{
assert(plist);
SeqListCheck(plist);
plist->a[plist->size] = x;
plist->size++;
}
void SeqListPopBack(SQList* plist)
{
assert(plist);
assert(plist->size > 0);
plist->size--;
}
void SeqListPushFront(SQList* plist, SQLDataType x)
{
assert(plist);
SeqListCheck(plist);
int cur = plist->size;
while (cur>0)
{
plist->a[cur] = plist->a[cur - 1];
cur--;
}
plist->a[cur] = x;
plist->size++;
}
void SeqListPopFront(SQList* plist)
{
assert(plist);
assert(plist->size > 0);
int end = 1;
while (end<plist->size)
{
plist->a[end - 1] = plist->a[end];
end++;
}
plist->size--;
}
int SeqListFrind(SQList* plist, SQLDataType x)
{
assert(plist);
int pos = 0;
while (pos < plist->size)
{
if (plist->a[pos] == x)
{
return pos;
}
else
{
pos++;
}
}
return -1;
}
void SeqListInsert(SQList* plist, int pos, SQLDataType x)
{
assert(plist);
SeqListCheck(plist);
int cur = plist->size;
while (cur > pos)
{
plist->a[cur] = plist->a[cur - 1];
cur--;
}
plist->a[cur] = x;
plist->size++;
}
void SeqListErase(SQList* plist, int pos)
{
assert(plist);
assert(plist->size > 0);
int end = pos;
while (end < plist->size-1)
{
plist->a[end ] = plist->a[end+1];
end++;
}
plist->size--;
}
总结
顺序表的优缺点
优点:
1.支持随机访问(可直接通过坐标访问)。
2.cpu高速缓存命中率高。
缺点:
1.空间不够需要扩容,扩容要付出代价。
2.避免扩容频繁,我们基本是满了就扩两倍,可能就导致一定的空间浪费。
3.顺序表要求数据从头开始连续存储,那么我们进行头删,头插数据时,需要挪动数据,效率不高。
上一篇: vue-python前后端下载文件