typedef int SLDateType;
typedef struct SeqList
{
SLDateType* a;
size_t size;
size_t capacity; // unsigned int
}SeqList;
// 对数据的管理:增删查改
void SeqListInit1(SeqList* ps)
{
if (ps == NULL)
return;
ps->a = NULL;
ps->size = ps->capacity = 0;
}
//销毁
void SeqListDestory1(SeqList* ps)
{
free(ps->a);
ps->a = NULL;
}
//打印
void SeqListPrint1(SeqList* ps)
{
if (ps == NULL)
return;
int size = ps->size;
for (int i = 0; i < size; i++)
{
printf("%d ", ps->a[i]);
}
}
//检查容量
void Checkcapacity1(SeqList* ps)
{
if (ps->size == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 1 : 2 * ps->capacity;
int* newa = (int*)realloc(ps->a, sizeof(int)*newcapacity);//realloc会自动释放原来的空间
ps->a = newa;
ps->capacity = newcapacity;
}
}
//尾插
void SeqListPushBack1(SeqList* ps, SLDateType x)
{
if (ps == NULL)
return;
//检查容量
Checkcapacity1(ps);
ps->a[ps->size] = x;
ps->size++;
}
//头插
void SeqListPushFront1(SeqList* ps, SLDateType x)
{
if (ps == NULL)
return;
Checkcapacity1(ps);
int end = ps->size;
while (end)
{
ps->a[end] = ps->a[end - 1];
}
ps->a[0] = x;
}
//头删
void SeqListPopFront1(SeqList* ps)
{
if (ps == NULL || ps->size == 0)
return;
int start = 1;
while (start < ps->size)
{
ps->a[start - 1] = ps->a[start];
++start;
}
--ps->size;
}
//尾删
void SeqListPopBack1(SeqList* ps)
{
if (ps == NULL)
return;
ps->size--;
}
// 顺序表查找
int SeqListFind1(SeqList* ps, SLDateType x)
{
Checkcapacity1(ps);
size_t i = 0;
for(i;i<ps->size;++i)
{
if (ps->a[i] == x)
return i;
}
return 0;
}
// 顺序表在pos位置插入x
void SeqListInsert1(SeqList* ps, int pos, SLDateType x)
{
if (ps == NULL)
return;
Checkcapacity1(ps);
int end = ps->size;
while (end > pos)
{
ps->a[end] = ps->a[end - 1];
end--;
}
ps->a[pos] = x;
ps->size++;
}
// 顺序表删除pos位置的值
void SeqListErase1(SeqList* ps, size_t pos)
{
if (ps == NULL)
return;
Checkcapacity1(ps);
while (pos < ps->size -1)
{
ps->a[pos] = ps->a[pos + 1];
pos++;
}
ps->size--;
}
void main()
{
SeqList ps;
SeqListInit1(&ps);
SeqListPushBack1(&ps, 1);
SeqListPushBack1(&ps, 2);
SeqListPushBack1(&ps, 3);
SeqListPushBack1(&ps, 4);
SeqListPushBack1(&ps, 5);
SeqListPrint1(&ps);
printf("\n");
SeqListPopBack1(&ps);
SeqListPrint1(&ps);
printf("\n");
SeqListPopFront1(&ps);
SeqListPrint1(&ps);
printf("\n");
SeqListInsert1(&ps, 2, 6);
SeqListPrint1(&ps);
printf("\n");
SeqListErase1(&ps, 2);
SeqListPrint1(&ps);
printf("\n");
int i = SeqListFind1(&ps, 1);
printf("%d ", i);
}
顺序表的增删改查等基本操作的实现
最新推荐文章于 2021-05-17 16:46:17 发布