头文件代码
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int Type;
typedef struct SeqList
{
Type* a;
int size;
int capacity;
}SL;
void SeqListInit(SL* ps);
void SeqListPrint(SL* ps);
void SeqListPushBack(SL* ps, Type x);
void SeqListpopBack(SL* ps);
void SeqListCheckCapacity(SL* ps);
void ShowCapacity(SL* ps);
void SeqListPushFront(SL* ps, Type x);
void SeqListPopFront(SL* ps);
int SeqListFind(SL* ps, Type x);
void SeqListInsert(SL* ps, int pos, Type x);
void SeqListErase(SL* ps, int pos);
源文件接口函数实现代码
#include"SeqList.h"
void SeqListInit(SL* ps)
{
ps->a = NULL;
ps->size = ps->capacity = 0;
}
void SeqListCheckCapacity(SL* ps)
{
if (ps->size == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
Type* tmp = (Type*)realloc(ps->a, newcapacity * sizeof(Type));
if (tmp == NULL)
{
printf("realloc fail\n");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
}
void SeqListPushBack(SL* ps, Type x)
{
SeqListCheckCapacity(ps);
ps->a[ps->size] = x;
ps->size++;
}
void ShowCapacity(SL* ps)
{
printf("\n%d ", ps->capacity);
}
void SeqListPrint(SL* ps)
{
for (int i = 0;i < ps->size;i++)
{
printf("%d ", ps->a[i]);
}
}
void SeqListpopBack(SL* ps)
{
assert(ps->size > 0);
ps->size--;
}
void SeqListPushFront(SL* ps, Type x)
{
SeqListCheckCapacity(ps);
int end = ps->size - 1;
while (end >= 0)
{
ps->a[end + 1] = ps->a[end];
--end;
}
ps->a[0] = x;
ps->size++;
}
void SeqListPopFront(SL* ps)
{
assert(ps->size > 0);
int begin = 1;
while (begin < ps->size)
{
ps->a[begin - 1] = ps->a[begin];
++begin;
}
ps->size--;
}
void SeqListInsert(SL* ps, int pos, Type x)
{
SeqListCheckCapacity(ps);
if (pos < 0 || pos > ps->size)
{
printf("pos invalid\n");
return;
}
int cha = ps->size - 1;
while (cha >= pos)
{
ps->a[cha + 1] = ps->a[cha];
--cha;
}
ps->size++;
ps->a[pos] = x;
}
void SeqListErase(SL* ps, int pos)
{
assert(ps->size > 0);
int ese = pos;
while (ese < ps->size - 1)
{
ps->a[ese] = ps->a[ese + 1];
++ese;
}
ps->size--;
}
int SeqListFind(SL* ps, Type x)
{
for (int i = 0;i < ps->size - 1;i++)
{
if (ps->a[i] == x)
{
return i;
}
}
return -1;
}
源文件主函数代码
#include"SeqList.h"
void test01()
{
SL s;
SeqListInit(&s);
SeqListPushBack(&s, 1);
SeqListPushBack(&s, 2);
SeqListPushBack(&s, 3);
SeqListPushBack(&s, 4);
SeqListPushBack(&s, 5);
SeqListpopBack(&s);
SeqListPrint(&s);
ShowCapacity(&s);
}
int main()
{
test01();
return 0;
}