结构:
sqlist.h:
顺序表元素:数组元素arr,元素个数size, 顺序表容量capacity
sqlist.c:
实现函数:创建init,输出print,尾插pushback,尾删popback,清空destroy;
#include"SeqList.h"
//初始化
void SLInit(SL* ps)
{
assert(ps);
ps->arr = NULL;
ps->capacity = 0;
ps->size = 0;
}
//输出
void SLPrint(SL* ps)
{
assert(ps);//判空
for (int i = 0; i < ps->size; i++)
{
printf("%d", ps->arr[i]);
}
printf("\n");
}
//删除
void SLDestroy(SL* ps)
{
assert(ps);
if (ps->arr)
{
free(ps->arr);
ps->arr = NULL;
ps->capacity = 0;
ps->size = 0;
}
}
//尾插
void SLPushBack(SL* ps, SLDataType x)
{
assert(ps);
if (ps->size == ps->capacity)
{
int newCapaCity = ps->capacity == 0 ? 4 : ps->capacity * 2;
SLDataType* temp = (SLDataType*)realloc(ps->arr, newCapaCity * sizeof(SLDataType));
if (temp == NULL)
{
perror("realloc erro");
exit(-1);
}
ps->arr = temp;
ps->capacity = newCapaCity;
}
ps->arr[ps->size] = x;
ps->size++;
}
//尾删
void SLPopBack(SL* ps)
{
assert(ps);
assert(ps->size>0);
//ps->arr[ps->size - 1] = NULL;//多余
ps->size--;
}
SeqList.c:
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
//静态顺序表
//#define N 10
typedef int SLDataType;
//typedef struct SeqList
//{
// SLDataType arr[N];
// int size;
//}SL;
//动态顺序表
typedef struct SeqList
{
SLDataType* arr;
int size;//元素个数
int capacity;//表长
}SL;
//创建
void SLInit(SL* ps);
//输出
void SLPrint(SL* ps);
//删除
void SLDestroy(SL* ps);
//尾插
void SLPushBack(SL* ps,SLDataType x);
//尾删
void SLPopBack(SL* ps);
test.c
#include"SeqList.h"
void TestSeqList()
{
SL sl;
SLInit(&sl);
SLPushBack(&sl, 1);
SLPushBack(&sl, 2);
SLPushBack(&sl, 3);
SLPushBack(&sl, 4);
SLPushBack(&sl, 5);
SLPushBack(&sl, 6);
SLPrint(&sl);
SLDestroy(&sl);
}
int main()
{
TestSeqList();
return 0;
}
test.c:
main中使用
注意:
assert暴力检查是否为空