静态顺序表
1静态顺序表:使用定长数组存储元素。 概念及结构
顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数据的增删查改。
动态顺序表
1.建立
在头文件
typedef int SLDataType;
#define INIT_CAPACITY 4
// 动态顺序表 -- 按需申请
typedef struct SeqList
{
SLDataType* a;//指向动态开辟的数组
int size; // 有效数据个数
int capacity; // 空间容量,用于判断是否需要扩容
}SL;
void SLInit(SL* ps);
void SLDestroy(SL* ps);
void SLPrint(SL* ps);
void SLPushBack(SL* ps, SLDataType x);
void SLPopBack(SL* ps);
void SLPushFront(SL* ps, SLDataType x);
void SLPopFront(SL* ps);
声明顺序表结构体,并且建立一个数组类型便于阅读,这里都是头文件的函数声明,也可以说是接口
#include"SeqList.h"
void SLInit(SL* ps)
{
ps->a = (SLDataType*)malloc(sizeof(SLDataType)* INIT_CAPACITY);
if (ps->a == NULL)
{
perror("malloc fail");
return;
}
ps->size = 0;
ps->capacity = INIT_CAPACITY;
}
线性变初始化,传递的是参数
2.删除
void SLDestroy(SL* ps)
{
free(ps->a);
ps->a = NULL;
ps->capacity = ps->size = 0;
}
简单来说就是把空间还回去。
3.扩容
void SLPushBack(SL* ps, SLDataType x)
{
// 扩容
if (ps->size == ps->capacity)
{
SLDataType* tmp = (SLDataType*)realloc(ps->a, sizeof(SLDataType)*ps->capacity * 2);
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity *= 2;
}
//ps->a[ps->size] = x;
//ps->size++;
ps->a[ps->size++] = x;
}
插入
void SLPushFront(SL* ps, SLDataType x)
{
/*assert(ps);
SLCheckCapacity(ps);
int end = ps->size - 1;
while (end >= 0)
{
ps->a[end + 1] = ps->a[end];
--end;
}
ps->a[0] = x;//插入的数据
ps->size++;*/
SLInsert(ps, 0, x);
}
头删法
void SLPopFront(SL* ps)
{
//assert(ps);
//assert(ps->size > 0);断言
//int begin = 1;
//while (begin < ps->size)
//{
// ps->a[begin - 1] = ps->a[begin];
// ++begin;
//}
//ps->size--;
SLErase(ps, 0);
}
从前往后移动,利用数组下标,最后把size移除
在一个位置插入一个数据
删除
void SLErase(SL* ps, int pos)
{
assert(ps);
assert(pos >= 0 && pos < ps->size);
1 int begin = pos + 1;
while (begin < ps->size)
{
ps->a[begin - 1] = ps->a[begin];
++begin;
}
ps->size--
查找并返回地址
int SLFind(SL* ps, SLDataType x)
{
assert(ps);
for(int i = 0; i < ps->size; ++i)
{
if (ps->a[i] == x)
{
return i;
}
}
return -1;
}