顺序表
一、顺序表
1.概念
2、动态顺序表:使用动态开辟的数组存储
二、顺序表的实现
1、接口的实现
(1)创建
(2)初始化
(3)扩容
(4)尾插
(5)尾删
(6)头插
(7)头删
(8)插入任意位置
(9)删除任意位置
(10)查找
(11)打印
三、完整代码
一、顺序表
1.概念
顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数据的增删查改。
动态顺序表:使用动态开辟的数组存储
二、顺序表的实现
1、接口的实现
(1)创建
为了养成模块化好习惯,我们尽量把代码分开来写。首先打开 VS2019,在解决方案资源管理器中的 “头文件” 文件夹中创建 SeqList.h 用来存放头文件。在 “源文件” 文件夹中创建 SeqList.c 用来实现函数,源.c 用来测试我们的顺序表:
(2)初始化
(3)扩容
(4)尾插
(5)尾删
(6)头插
(7)头删
(8)插入任意位置
(9)删除任意位置
(10)查找
(11)打印
三、完整代码
#include"SeqList.h"
void SLInit(SL *ps)
{
ps->arr =(int*)malloc(sizeof(int)*INIT_capacity);
if (ps->arr == NULL)
{
perror("malloc fail");
return;
}
ps->s = 0;
ps->capacity = INIT_capacity;
}
void SLDestroy(SL* ps)
{
free(ps->arr);
ps->arr = NULL;
ps->s = 0;
ps->capacity = 0;
}
void SLprint(SL* ps)
{
for (int i = 0; i < ps->s; i++)
{
printf("%d ", ps->arr[i]);
}
printf("\n");
}
void SLPushBack(SL* ps, int x)
{
SLcheckcapacity(ps);
ps->arr[ps->s++] = x;
}
void SLPopBack(SL* ps)
{
if (ps->s == 0)
return;
ps->s--;
}
void SLPushFront(SL* ps, int x)
{
int end = ps->s - 1;
while (end >= 0)
{
ps->arr[end + 1] = ps->arr[end];
end--;
}
ps->arr[0] = x;
ps->s++;
}
void SLcheckcapacity(SL* ps)
{
if (ps->s == ps->capacity)
{
int* tmp = (int*)realloc(ps->arr, sizeof(int) * ps->capacity * 2);
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->arr = tmp;
ps->capacity *= 2;
}
}
void SLPopFront(SL* ps)
{
assert(ps->s > 0);
int begin = 1;
while (begin < ps->s)
{
ps->arr[begin - 1] = ps->arr[begin];
begin++;
}
ps->s--;
}
void SLInsert(SL* ps, int pos, int x)
{
assert(ps);
assert(pos >=0&&pos<=ps->s);
SLcheckcapacity(ps);
int end = ps->s - 1;
while (end >= pos)
{
ps->arr[end + 1] = ps->arr[end];
end--;
}
ps->arr[pos] = x;
ps->s++;
}
void SLErase(SL* ps, int pos)
{
assert(ps);
assert(pos >= 0 && pos < ps->s);
int begin = pos+1;
while (begin < ps->s)
{
ps->arr[begin - 1] = ps->arr[begin];
begin++;
}
ps->s--;
}
void SLFind(SL* ps, int x)
{
assert(ps);
for (int i = 0; i < ps->s; i++)
{
if (ps->arr[i] == x)
{
return i;
}
return -1;
}
}