文章目录
一、线性表
线性表(linear list)是n个具有相同特性的数据元素的有限序列。 线性表是一种在实际中广泛使用的数据结构,常见的线性表:顺序表、链表、栈、队列、字符串…
线性表在逻辑上是线性结构,也就说是连续的一条直线。但是在物理结构上并不一定是连续的,线性表在物理上存储时,通常以数组和链式结构的形式存储。
线性表的结构
二、什么是顺序表
顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数据的增删查改。
顺序表一般分为静态顺序表和动态顺序表。
1.静态顺序表:使用定长数组存储数据
#define MAX 100 //数组的最大长度
typedef int SLDtataType; //重命名数据类型
typedef struct SeqList
{
SLDtataType data[MAX]; //使用定长数组来存储数据
size_t size; //有效数据的个数
}SL;
2.动态顺序表:使用动态开辟存储数据
typedef int SLDateType;
typedef struct SeqList
{
SLDateType* a;
int size;
int capacity;
}SL;
三、顺序表的接口实现
杂项
结构定义
typedef int SLDateType;
typedef struct SeqList
{
SLDateType* a;
int size;
int capacity;
}SL;
顺序表的打印
void Print(SL* psl)
{
for (int i = 0; i < psl->size; i++)
{
printf("%d ", psl->a[i]);
}
printf("\n");
}
顺序表的空间检查
void SeqListCheck(SL* psl)
{
assert(psl);
if (psl->capacity == psl->size)
{
int NewCapacity = psl->capacity == 0 ? 4 : psl->capacity * 2;
SLDateType tmp = realloc(psl->a, NewCapacity * sizeof(SLDateType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
psl->a = tmp;
psl->capacity = NewCapacity;
}
}
1.顺序表的初始化
void SeqListInit(SL* psl);
void SeqListInit(SL* psl)
{
assert(psl);
psl->a = NULL;
psl->capacity = psl->size = 0;
}
2.顺序表的销毁
void SeqListDestory(SL* psl);
void SeqListDestory(SL* psl)
{
assert(psl);
free(psl->a);
psl->a = NULL;
psl->capacity = psl->size = 0;
}
3.顺序表的尾部插入(尾插)
void SeqListPushBack(SL* psl, SLDateType x);
void SeqListPushBack(SL* psl, SLDateType x)
{
assert(psl);
SeqListCheck(psl);
psl->a[psl->size] = x;
psl->size++;
}
4.顺序表的尾部删除(尾删)
void SeqListPopBack(SL* psl);
void SeqListPopBack(SL* psl)
{
assert(psl);
assert(psl->size > 0);
psl->size--;
}
5.顺序表的头部插入(头插)
void SeqListPushfront(SL* psl, SLDateType x);
void SeqListPushfront(SL* psl, SLDateType x)
{
assert(psl);
SeqListCheck(psl);
int end = psl->size - 1;
while (end >= 0)
{
psl->a[end + 1] = psl->a[end];
end--;
}
psl->a[0] = x;
psl->size++;
}
6.顺序表的头部删除
void SeqListPopfront(SL* psl);
void SeqListPopfront(SL* psl)
{
assert(psl);
assert(psl->size > 0);
int begin = 0;
while (begin < psl->size - 1)
{
psl->a[begin] = psl->a[begin + 1];
begin++;
}
psl->size--;
}
7.顺序表的查找
int SeqListFind(SL* psl, SLDateType x);
int SeqListFind(SL* psl, SLDateType x)
{
assert(psl);
for (int i = 0; i < psl->size; i++)
{
if (psl->a[i] == x)
return i;
}
return -1;
}
8.顺序表的pos位置插入x
void SeqListInsert(SL* psl, size_t pos, SLDateType x);
void SeqListInsert(SL* psl, size_t pos, SLDateType x)
{
assert(psl);
assert(pos < psl->size);
SeqListCheck(psl);
size_t end = psl->size;
while (end > pos)
{
psl->a[end] = psl->a[end - 1];
end--;
}
psl->a[pos] = x;
psl->size++;
}
9.顺序表的pos位置删除
void SeqListErase(SL* psl, size_t pos);
void SeqListErase(SL* psl, size_t pos)
{
assert(psl);
size_t begin = pos;
while (begin < psl->size - 1)
{
psl->a[begin] = psl->a[begin+1];
begin++;
}
psl->size--;
}