SeqList.h:
功能:
#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#define Init_Capacity 4 //初始容量
typedef int SLDateType; //数据类型
typedef struct SeqList //储存动态顺序表
{
SLDateType* a; //动态顺序表
int size; //已存数据数量
int capacity; //当前最大容量
}SL;
//开辟顺序表
void SeqListInit(SL* s);
//销毁顺序表
void SeqListDestroy(SL* s);
//检查顺序表容量
void SeqListCheckCapacity(SL* s);
//打印顺序表
void SeqListPrint(SL* s);
// 对数据的管理
//尾插
void SeqListPushBack(SL* s, SLDateType x);
//头插
void SeqListPushFront(SL* s, SLDateType x);
//尾删
void SeqListPopBack(SL* s);
//头删
void SeqListPopFront(SL* s);
// 顺序表查找
int SeqListFind(SL* s, SLDateType x);
// 顺序表在pos位置插入x
void SeqListInsert(SL* s, int pos, SLDateType x);
// 顺序表删除pos位置的值
void SeqListErase(SL* s, int pos);
SeqList.c:
开辟顺序表内存:
// 开辟顺序表内存
void SeqListInit(SL* s)
{
s->a = (SLDateType*)malloc(sizeof(SLDateType) * Init_Capacity);
if (s->a == NULL)
{
perror("malloc fail:");
return;
}
s->capacity = Init_Capacity; //申请的容量
s->size = 0;
}
///
销毁顺序表内存:
(养成申请内存就立马想到销毁内存的思想)
// 销毁顺序表
void SeqListDestroy(SL* s)
{
if (s->a == NULL) //判断顺序表是否为空
return; //为空则跳出
free(s->a);
s->a = NULL;
s->capacity = s->size = 0;
}
/
检查顺序表当前容量:
// 检查顺序表容量
void SeqListCheckCapacity(SL* s)
{
assert(s);
if (s->size == s->capacity) //判断当前容量是否已满
{
SLDateType* tmp = (SLDateType*)realloc(s->a,sizeof(SLDateType) * (s->capacity + Init_Capacity));
if (tmp == NULL)
{
perror("malloc fail:");
return;
}
s->a = tmp;
s->capacity += Init_Capacity;
}
}
/
打印顺序表:
// 打印顺序表
void SeqListPrint(SL* s)
{
assert(s);
for (int i = 0; i < s->size; ++i)
{
printf("%d ",s->a[i]);
}
printf("\n");
}
///
在顺序表尾部插入数据:
// 尾插
void SeqListPushBack(SL* s, SLDateType x)
{
if (s.capacity == s.size) //需扩容
SeqListCheckCapacity(s);
s->a[s->size++] = x;
}
//
在顺序表首部插入数据:
// 头插
void SeqListPushFront(SL* s, SLDateType x)
{
assert(s);
SeqListCheckCapacity(s);
int end = s->size - 1;
while (end >= 0) //将原有数据后移
{
s->a[end + 1] = s->a[end];
end--;
}
s->a[0] = x;
s->size++;
}
删除顺序表尾部数据:
// 尾删
void SeqListPopBack(SL* s)
{
assert(s);
assert(s->size);
s->size--; //直接size - 1即可
}
删除顺序表首部数据:
// 头删
void SeqListPopFront(SL* s)
{
assert(s);
for (int start = 0; start <= s->size - 2; ++start) //从第二个数据开始,前移
{
s->a[start] = s->a[start + 1];
}
s->size--;
}
/
顺序表查找数据x:
// 顺序表查找
int SeqListFind(SL* s, SLDateType x)
{
assert(s);
assert(s->a); //判断顺序表是否为空
int cur = 0;
while (s->a[cur] != x && cur < s->size)
{
cur++;
}
if (s->a == x)
return cur;
else
return -1;
}
///
顺序表pos位置插入数据x:
// 顺序表在pos位置插入x
void SeqListInsert(SL* s, int pos, SLDateType x)
{
assert(s);
assert(pos >= 0 && pos <= s->size); //判断pos位置是否在顺序表内
SeqListCheckCapacity(s); //判断是否需要扩容
int end = s->size - 1;
while (end >= pos)
{
s->a[end + 1] = s->a[end];
end--;
}
s->a[pos] = x;
s->size++;
}
删除顺序表pos位置的数据:
// 顺序表删除pos位置的数据
void SeqListErase(SL* s, int pos)
{
assert(s);
assert(pos >= 0 && pos < s->size); //判断pos位置是否在顺序表内
for (int start = pos + 1; pos <= s->size - 1; ++start)
{
s->a[start - 1] = s->a[start];
}
s->size--;
}