一、创建头文件
typedef int SLDataType;
//动态存储
typedef struct SeqList
{
SLDataType* a; //动态开辟的数组
int size; //有效数据的数量
int capacity; //空间大小
}SL;
二、初始化顺序表
void SLInit(SL* psl)
{
assert(psl);
psl->a = NULL;
psl->size = 0;
psl->capacity = 0;
}
三、 销毁顺序表
void SLDestory(SL* psl)
{
assert(psl);
if (psl->a != NULL)
{
free(psl->a);
psl->a = NULL;
psl->size = 0;
psl->capacity = 0;
}
}
四、打印顺序表
void SLPrint(SL* psl)
{
assert(psl);
for (int i = 0; i < psl->size; i++)
printf("%d ", psl->a[i]);
printf("\n");
}
五、给顺序表开辟空间
void SLCheckCapacity(SL* psl)
{
assert(psl);
//如果有效数字和总容量相等,则进入判断语句
if (psl->size == psl->capacity)
{
//若总容量为零,则给四个空间;若不为零,则在原有空间基础上扩容两倍。
int newCapacity = psl->capacity == 0 ? 4 : psl->capacity * 2;
SLDataType* tmp = (SLDataType*)realloc(psl->a, sizeof(SLDataType) * newCapacity);
if (tmp == NULL)
{
perror("realloc fail");
return;
}
//扩容成功
psl->a = tmp;
psl->capacity = newCapacity;
}
}
六、对顺序表进行尾插
SL sl;
SLInit(&sl);
SLPushBack(&sl, 1);
SLPushBack(&sl, 2);
SLPushBack(&sl, 3);
SLPushBack(&sl, 4);
SLPushBack(&sl, 5);
SLPrint(&sl);
void SLPushBack(SL* psl, SLDataType x)
{
assert(psl);
SLCheckCapacity(psl);
psl->a[psl->size] = x;
psl->size++;
}
流程图:
每次进行尾插的时候都是进行一样的方法
七、对顺序表进行头插
SL sl;
SLInit(&sl);
SLPushBack(&sl, 1);
SLPushBack(&sl, 2);
SLPushBack(&sl, 3);
SLPushBack(&sl, 4);
SLPushBack(&sl, 5);
SLPrint(&sl);
SLPushFront(&sl, 10);
SLPushFront(&sl, 20);
SLPushFront(&sl, 30);
SLPushFront(&sl, 40);
SLPrint(&sl);
void SLPushFront(SL* psl, SLDataType x)
{
assert(psl);
SLCheckCapacity(psl);
int end = psl->size - 1;
while (end >= 0)
{
psl->a[end + 1] = psl->a[end];
--end;
}
psl->a[0] = x;
psl->size++;
}
流程图:
八、 对顺序表进行尾删
void SLPopBack(SL* psl)
{
assert(psl);
assert(psl->size > 0);
psl->size--;
}
assert(psl->size > 0);是为了判断当前顺序表是否存在数据
流程图:
九、对顺序表进行头删
void SLPopFront(SL* psl)
{
assert(psl);
assert(psl->size > 0);
int begin = 1;
while (begin < psl->size)
{
psl->a[begin - 1] = psl->a[begin];
++begin;
}
psl->size--;
}
psl->a[begin] 在这里,因为变量begin给了数字1,便从数组中1的下标开始
流程图:
十、在顺序表中,对指定下标位置插入元素
void SLInsert(SL* psl, int pos, SLDataType x)
{
assert(psl);
assert(pos >= 0 && pos <= psl->size);
SLCheckCapacity(psl);
int end = psl->size - 1;
//找到下标位置并进行挪移
while (end >= pos)
{
psl->a[end + 1] = psl->a[end];
--end;
}
//挪移完成后,当前下标位置为空,将元素给到这个下标
psl->a[pos] = x;
psl->size++;
}
流程图:
十一、 在顺序表中,在指定下标的元素删除
void SLErase(SL* psl, int pos)
{
assert(psl);
assert(pos >= 0 && pos < psl->size);
int begin = pos + 1;
while (begin < psl->size)
{
psl->a[begin - 1] = psl->a[begin];
++begin;
}
psl->size--;
}
流程图:
感谢观看,如觉得作者能让你看得明白,点个三连吧!!!