赞
踩
线性表(linear list)是n个具有相同特性的数据元素的有限序列。
顺序表是用一段物理地址连续的存储单元
依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数据的增删改查。
顺序表一般可以分为:
所以下面我们实现动态顺序表:
静态
#define N 10
typedef int SLDataType;
typedef struct SeqList
{
int size;//有效数据的个数
SLDataType arr[N];//指向开辟的数组
}SeqList;
动态
//动态顺序表
typedef int SLDataType;
typedef struct SeqList
{
int size;//已存储数据的个数
int capacity; //容量
SLDataType* arr;//指向动态开辟的数组
}SeqList;
void InitSeqList(SeqList* ps)
{
assert(ps);
ps->arr = NULL;
ps->capacity = 0;
ps->size = 0;
}
如果满了,进行扩容
void CheckCapcity(SeqList* ps) { assert(ps); //存储的数据和容量相等了,增加容量 if (ps->capacity == ps->size) { //若起始容量为0,则将容量设置为4,否则二倍的形式错容; int newCapacity = ps->capacity == 0 ? 4 : (2 * ps->capacity); SLDataType* tmp = (SLDataType*)realloc(ps->arr, newCapacity * sizeof(SLDataType)); if (tmp == NULL) { perror("CheckCapcity():realloc()"); return; } ps->arr = tmp; ps->capacity = newCapacity; } }
//打印
void SeqListPrint(SeqList* ps)
{
int i = 0;
for (i = 0; i < ps->size; i++)
{
printf("%d ", ps->arr[i]);
}
printf("\n");
}
//尾插
void SeqListPushBack(SeqList* ps, SLDataType x)
{
assert(ps);
//先检查当前容量
CheckCapcity(ps);
//插入
ps->arr[ps->size] = x;
ps->size++;
}
//头插
void SeqListPushFront(SeqList* ps, SLDataType x)
{
assert(ps);
//先检查容量
CheckCapcity(ps);
//旧数据往后挪
for (int i = ps->size; i > 0; i--)
{
ps->arr[i] = ps->arr[i - 1];
}
ps->arr[0] = x;
ps->size++;
}
//尾删
void SeqListPopBack(SeqList* ps)
{
assert(ps);
//得有数据
assert(ps->size);
//ps->arr[ps->size - 1] = -1;
ps->size--;
}
//头删
void SeqListPopFront(SeqList* ps)
{
assert(ps);
assert(ps->size);
int i = 0;
for (i = 0; i < ps->size - 1; i++)
{
ps->arr[i] = ps->arr[i + 1];
}
ps->size--;
}
//查找
int SeqListFind(SeqList* ps, SLDataType x)
{
assert(ps);
int i = 0;
for (i = 0; i < ps->size; i++)
{
if (ps->arr[i] == x)
{
return i;
}
}
return -1;
}
// 在pos位置插入x void SeqListInsert(SeqList* ps, int pos, SLDataType x) { assert(ps); //位置合理 assert(pos >= 0 && pos <= ps->size); CheckCapcity(ps); int i = 0; //pos及之后的数据往后挪 for (i = ps->size; i > pos; i--) { ps->arr[i] = ps->arr[i - 1]; } ps->arr[pos] = x; ps->size++; }
// 删除pos位置的值
void SeqListErase(SeqList* ps, int pos)
{
assert(ps);
assert(pos >= 0 && pos < ps->size);
int i = 0;
for (i = pos; i < ps->size - 1; i++)
{
ps->arr[i] = ps->arr[i + 1]; //arr[size-2] = arr[size - 1]
}
ps->size--;
}
void SeqListDestory(SeqList* ps)
{
assert(ps);
if (ps->arr)
{
free(ps->arr);
}
ps->arr = NULL;
ps->size = 0;
ps->capacity = 0;
}
顺序表就到这里啦~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。