顺序表
1.线性表
线性表(linear list)是n个具有相同特性的数据元素的有限序列。 线性表是一种在实际中广泛使用的数据结构,常见的线性表:顺序表、链表、栈、队列、字符串…
线性表在逻辑上是线性结构,也就说是连续的一条直线。但是在物理结构上并不一定是连续的,线性表在物理上存储时,通常以数组和链式结构的形式存储。
顺序表
链表
2.顺序表
2.1概念及结构
顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存
储。在数组上完成数据的增删查改。
顺序表一般可以分为:
- 静态顺序表:使用定长数组存储元素。
- 动态顺序表:使用动态开辟的数组存储
2.2 接口实现
静态顺序表只适用于确定知道需要存多少数据的场景。静态顺序表的定长数组导致N定大了,空间开多了浪费,开少了不够用。所以现实中基本都是使用动态顺序表,根据需要动态的分配空间大小,所以下面我们实现动态顺序表。
typedef int SLDataType;
// 顺序表的动态存储
typedef struct SeqList
{
SLDataType* array; // 指向动态开辟的数组
size_t size ; // 有效数据个数
size_t capicity ; // 容量空间的大小
}SeqList;
2.2.1顺序表初始化
void SeqListInit(SeqList* ps)
{
assert(ps);
ps->a = NULL;
ps->size = 0;
ps->capacity = 0;
}
2.2.2检查空间
void SeqListCheck(SeqList* ps)
{
if (ps->size == ps->capacity)
{
int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
SLDateType* temp = (SLDateType*)realloc(ps->a, newCapacity * sizeof(SeqList));
if (temp == NULL)
{
perror("realloc fail");
exit(-1);
}
ps->a = temp;
ps->capacity = newCapacity;
}
}
2.2.3顺序表尾插和尾删
//尾插
void SeqListPushBack(SeqList* ps, SLDateType x)
{
assert(ps);
SeqListCheck(ps);
ps->a[ps->size] = x;
ps->size++;
}
//尾删
void SeqListPopBack(SeqList* ps)
{
assert(ps);
assert(ps->size > 0);
ps->size--;
}
2.2.4顺序表头插和头删
//头插
void SeqListPushFront(SeqList* ps, SLDateType x)
{
assert(ps);
SeqListCheck(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(SeqList* ps)
{
assert(ps);
assert(ps->size > 0);
int begin = 1;
while (begin < ps->size)
{
ps->a[begin - 1] = ps->a[begin];
begin++;
}
ps->size--;
}
2.2.5顺序表查找和销毁
//查找
int SeqListFind(SeqList* ps, SLDateType x)
{
assert(ps);
int i = 0;
for (i = 0; i < ps->size; ++i)
{
if (ps->a[i] == x)
{
return i;
}
}
return -1;
}
//销毁
void SeqListDestroy(SeqList* ps)
{
assert(ps);
if (ps->a)
{
free(ps->a);
ps->a = NULL;
ps->size = 0;
ps->capacity = 0;
}
}
2.2.6顺序表打印
void SLPrint(SeqList* ps)
{
assert(ps);
for (int i = 0; i < ps->size; ++i)
{
printf("%d ", ps->a[i]);
}
printf("\n");
}
2.2.7顺序表在pos位置的插入和删除
// 顺序表插入pos位置的值
void SeqListInsert(SeqList* ps, size_t pos, SLDateType x)
{
assert(ps);
assert(ps>=0);
assert(pos <= ps->size);
SeqListCheck(ps);
size_t end = ps->size;
while (end > pos)
{
ps->a[end] = ps->a[end - 1];
--end;
}
ps->a[pos] = x;
++ps->size;
}
// 顺序表删除pos位置的值
void SeqListErase(SeqList* ps, size_t pos)
{
assert(ps);
assert(pos < ps->size);
size_t begin = pos;
while (begin < ps->size - 1)
{
ps->a[begin] = ps->a[begin + 1];
++begin;
}
ps->size--;
}