顺序表的结构
顺序表的本质是一个连续的数组用来存储数据。
顺序表可分为静态顺序表(空间固定)和动态顺序表(空间可连续开辟)
顺序表的接口函数
数组的初始化:
SeqListInit(SL*ps);
顺序表的打印:
SeqListPrint(SL*ps);
元素的尾插尾删:
SeqListPushBack(SL*ps,SeqListDataType x);
SeqListPopBack(SL*ps);
元素的头插头删:
SeqListPushFront(SL*ps,SeqListDataType x);
SeqListPopFront(SL*ps);
元素的查找:
SeqListFind(SL*ps,SeqListDataType x);
元素指定位置的插入:
SeqListInset(SL* ps, int pos, SLDataType x);
删除指定位置的元素:
SeqListEarse(SL* ps, int pos);
空间的销毁:
SeqListDestory(SL* ps);
接口函数的实现
typedef int SLDataType;
//动态顺序表
typedef struct SeqList
{
SLDataType* a;//开辟空间的起始位置
int size;//表示数组中元素个数,存储了多少个数据
int capacity;//表示实际存数据的空间有多大
}SL;
void SeqListInt(SL* ps)
{
ps->a = NULL;
ps->capacity = ps->size = 0;
//size可以初始化为0,这时size表示的是数组中元素个数;size也可初始化为-1,这时size表示数组中元素的下标
}
void SeqListCheck(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)
{
perror("tmp");
exit(-1);
}
ps->capacity = newcapacity;
ps->a = tmp;
}
}
void SeqListPrint(SL* ps)
{
int i = 0;
for (i = 0; i < ps->size; i++)
{
printf("%d ", ps->a[i]);
//Sleep(1000);
}
//printf("\n");
}
void SeqListPushBack(SL* ps, SLDataType x)
{
SeqListCheck(ps);
//空间足够
ps->a[ps->size] = x;
ps->size++;
//SeqListInset(ps, ps->size, x);
}
void SeqListPopBack(SL* ps)
{
//if (ps->size > 0)
//{
//ps->size-- ;
//}
assert(ps->size>0);
ps->size--;
}
void SeqListPushFront(SL* ps, SLDataType x)
{
//头插需要将数据全部往后挪一位
SeqListCheck(ps);
//先挪最后一个,依次往前
int end = ps->size-1;
while (end>=0)
{
ps->a[end + 1] = ps->a[end];
end--;
}
ps->a[0] = x;
ps->size++;
//SeqListInset(ps, 0, x);
}
Void SeqListPopFront(SL*ps)
{
//头删只需要把头元素后的元素依次往前挪
int count=0;
while(count<ps->size-1)
{
ps->a[count]=ps->a[count+1];
count++;
}
ps->size--;
}
//寻找元素所在位置
int SeqListFind(SL* ps, SLDataType x)
{
int i = 0;
for (i = 0; i < ps->size; i++)
{
if (ps->a[i] == x)
{
return i;
}
}
}
void SeqListInset(SL* ps, int pos, SLDataType x)
{
/*if (pos > ps->size || pos < 0)
{
printf("pos值错误");
return -1;
}*/
assert(pos <= ps->size && pos >= 0);
SeqListCheck(ps);
int tmp = ps->size;
//将pos之后的元素往后挪给pos位置的插入留出空间
while (tmp!=pos)
{
ps->a[tmp] = ps->a[tmp - 1];
tmp--;
}
ps->a[tmp] = x;
ps->size++;
}
void SeqListEarse(SL* ps, int pos)
{
assert(pos <= ps->size && pos >= 0);
while (pos!=ps->size -1)
{
ps->a[pos] = ps->a[pos + 1];
pos++;
}
ps->size--;
}
顺序表的缺陷
1,元素的插入删除有时需要挪动数据较为麻烦
2,需要连续开辟空间有时会造成空间的浪费
顺序表的优点
1,支持随机访问,对于需要支持随机访问结构的算法可以很好的使用。、
2,CPU高速缓存命中率高。