SeqlistD.h
#ifndef __SEQLISTD_H__
#define __SEQLISTD_H__
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<string.h>
typedef int DataType;
#define SZ 3
typedef struct Seqlist
{
DataType* data;
int sz;
int capacitance;
}Seqlist,*pSeqlist;
int Empty(pSeqlist pSeq);
void Popback(pSeqlist pSeq);
void DestorySeqlist(pSeqlist pSeq);
void CheckCapciaty(pSeqlist pSeq);
void InitSeqlist(pSeqlist pSeq);
void PrintSeqlist(pSeqlist pSeq);
void Pushback(pSeqlist pSeq, DataType d);
#endif
SeqlistD.c
#include "SeqlistD.h"
void InitSeqlist(pSeqlist pSeq)
{
assert(pSeq != NULL);
pSeq->data = (DataType *)malloc(SZ*sizeof(DataType));//动态开辟
if (pSeq->data == NULL)
{
perror("use malloc");
exit(EXIT_FAILURE);
}
pSeq->sz = 0;
pSeq->capacitance = SZ;
}
void PrintSeqlist(pSeqlist pSeq)
{
int i = 0;
assert(pSeq != NULL);
for (i = 0; i < pSeq->sz; i++)
{
printf("%d ", pSeq->data[i]);
}
printf("\n");
}
void Pushback(pSeqlist pSeq, DataType d)
{
assert(pSeq != NULL);
CheckCapciaty(pSeq);
pSeq->data[pSeq -> sz] = d;
pSeq->sz++;
}
void CheckCapciaty(pSeqlist pSeq)//检查是否增容
{
assert(pSeq != NULL);
if (pSeq->sz == pSeq->capacitance)
{
DataType * tmp = (DataType *)realloc(pSeq->data, (pSeq->capacitance + 2)*sizeof(DataType));
if (tmp != NULL)
{
pSeq->data = tmp;
}
pSeq->capacitance += 2;
printf("增容成功\n");
}
}
void DestorySeqlist(pSeqlist pSeq)
{
assert(pSeq != NULL);
free(pSeq->data);
pSeq->data = NULL;
pSeq->sz = 0;
pSeq->capacitance = 0;
}
void Popback(pSeqlist pSeq)
{
assert(pSeq != NULL);
/*if (pSeq->sz == 0)
{
printf("顺序表为空,无法删除");
return;
}*/
if (Empty(pSeq))
{
printf("顺序表为空,无法删除");
}
pSeq->sz--;
}
int Empty(pSeqlist pSeq)
{
return pSeq->sz == 0;
}
Test.c
#include "SeqlistD.h"
void test()
{
Seqlist seq;
InitSeqlist(&seq);
Pushback(&seq, 1);
Pushback(&seq, 4);
Pushback(&seq, 13);
Pushback(&seq, 15);
PrintSeqlist(&seq);
Popback(&seq);
PrintSeqlist(&seq);
DestorySeqlist(&seq);
}
int main()
{
test();
system("pause");
}