顺序表的定义
顺序表使用一段物理地址连续的存储单元依次存储数据元素,常使用数组实现。
顺序表一般可以分为静态顺序表和动态顺序表。
静态顺序表只适用于确定知道需要存多少数据的场景,使用起来有较大的局限性。 所以现实中基本都是用动态顺序表,根据需要动态的分配空间大小。
顺序表的实现:
Squeue table.h
typedef int SLDataType;
typedef struct SeqList
{
SLDataType* a;
int size; //有效数据
int capacity; //空间容量
}SL;
void SLInit(SL* sp1);
void SLDestroy(SL* ps1);
void SLPrint(SL* ps1);
void SLCheckCapacity(SL* ps1);
//头尾插入删除
void SLPushBack(SL* ps1, SLDataType x);
void SLPushFront(SL* ps1, SLDataType x);
void SLPopBack(SL* ps1, SLDataType x);
void SLPopFront(SL* ps1);
//任意下标位置插入
void SLInsert(SL* ps1, int pos, SLDataType x);
void SLErase(SL* ps1, int pos);
//查找
//找到返回下标
//没找到返回-1
int SLFind(SL* ps1, SLDataType x);
Squeue table.c
#include "Squence list.h"
//初始化
void SLInit(SL* ps1)
{
assert(ps1);
ps1->a = NULL;
ps1->size = 0;
ps1->capacity = 0;
}
//销毁
void SLDestroy(SL* ps1)
{
assert(ps1);
if (ps1->a != NULL)
{
free(ps1->a);
ps1->a = NULL;
ps1->size = 0;
ps1->capacity = 0;
}
}
//打印
void SLPrint(SL* ps1)
{
assert(ps1);
for (int i = 0; i < ps1->size; i++)
{
printf("%d ", ps1->a[i]);
}
printf("\n");
}
//扩容
void SLCheckCapacity(SL* ps1)
{
assert(ps1);
if (ps1->size == ps1->capacity)
{
int nwecapacity = ps1->capacity == 0 ? 4 : ps1->capacity * 2;
SLDataType* tmp = (SLDataType*)realloc(ps1->a, sizeof(SLDataType) * nwecapacity);
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps1->a = tmp;
ps1->capacity = nwecapacity;
}
}
//尾插
void SLPushBack(SL* ps1, SLDataType x)
{
assert(ps1);
SLCheckCapacity(ps1);
ps1->a[ps1->size] = x;
ps1->size++;
}
//头插
void SLPushFront(SL* ps1, SLDataType x)
{
assert(ps1);
SLCheckCapacity(ps1);
int end = ps1->size - 1;
while (end >= 0)
{
ps1->a[end + 1] = ps1->a[end];
--end;
}
ps1->a[0] = x;
ps1->size++;
}
//尾删
void SLPopBack(SL* ps1)
{
assert(ps1);
assert(ps1->size > 0);
ps1->size--;
}
//头删
void SLPopFront(SL* ps1)
{
assert(ps1);
assert(ps1->size > 0);
int begin = 1;
while (begin < ps1->size)
{
ps1->a[begin - 1] = ps1->a[begin];
++begin;
}
ps1->size--;
}
//指定位置插入
void SLInsert(SL* ps1, int pos, SLDataType x)
{
assert(ps1);
assert(pos >= 0 && pos <= ps1->size);
SLCheckCapacity(ps1);
int end = ps1->size - 1;
while (end >= pos)
{
ps1->a[end + 1] = ps1->a[end];
--end;
}
ps1->a[pos] = x;
ps1->size++;
}
//指定位置删除
void SLErase(SL* ps1, int pos)
{
assert(ps1);
assert(pos >= 0 && pos <= ps1->size);
int begin = pos + 1;
while (begin < ps1->size)
{
ps1->a[begin - 1] = ps1->a[begin];
++begin;
}
ps1->size--;
}
//查找
int SLFind(SL* ps1, SLDataType x)
{
assert(ps1);
for (int i = 0; i < ps1->size; i++)
{
if (ps1->a[i] == x)
{
return i;
}
}
return -1;
}