[数据结构] 动态顺序表应用
可扩容顺序表顺序表
- SeqList.h
- SeqList.c
- Test.c
动态顺序表能够根据数据存储的需要动态地管理内存空间。
SeqList.h
#include<stdio.h>
#include<stdlib.h>
//静态顺序表
//小了不够用,多了浪费
//#define N 10
//typedef int SLDatatype;
//struct SeqList
//{
// SLDatatype a[N];
// int size;
//
//};
typedef int SLDatatype;
typedef struct SeqList
{
SLDatatype* a;
int size;//数据个数
int capacity;//容量
}SL;
void SLInit(SL* psl);
void SLDestory(SL* psl);
void SLPrint(SL* psl);
void SLPushBack(SL* psl, SLDatatype x);
void SLPushFront(SL* psl, SLDatatype x);
void SLPopBack(SL* psl);
void SLPopBack(SL* psl);
SeqList.c
#include"SeqList.h"
void SLInit(SL *psl) {
psl->a = (SLDatatype*)malloc(sizeof(SLDatatype) * 4);
if (psl->a == NULL) {
perror("malloc fail");
return 0;
}
psl->capacity = 4;
psl->size = 0;
}
void SLDestory(SL* psl) {
free(psl->a);
psl->a = NULL;
psl->size = 0;
psl->capacity = 0;
}
void SLPrint(SL* psl) {
for (int i = 0; i < psl->size; i++) {
printf("%d ", psl->a[i]);
}
printf("\n");
}
void SLCheckCapacity(SL* psl) {
if (psl->size == psl->capacity) {
SLDatatype* tmp = realloc(psl->a, sizeof(SLDatatype) * psl->capacity * 2);
if (tmp == NULL) {
perror("realloc fail");
return 0;
}
psl->a = tmp;
psl->capacity *= 2;
}
}
void SLPushBack(SL* psl, SLDatatype x) {//尾部数据插入
SLCheckCapacity(psl);
psl->a[psl->size] = x;
psl->size++;
}
void SLPushFront(SL* psl, SLDatatype x);
void SLPopBack(SL* psl);
void SLPopBack(SL* psl);
Test.c
#include"SeqList.h"
int main() {
SL s;
SLInit(&s);
SLPushBack(&s, 1);
SLPushBack(&s, 2);
SLPushBack(&s, 3);
SLPushBack(&s, 4);
SLPushBack(&s, 5);
SLPushBack(&s, 6);
SLPushBack(&s, 6);
SLPushBack(&s, 6);
SLPushBack(&s, 6);
SLPrint(&s);
SLDestory(&s);
return 0;
}