#include<cstdlib>
#include <cstdio>
#define InitSize 10 //默认的最大长度
typedef struct
{
int *data; //指示动态分配数组的指针
int MaxSize; //顺序表的最大容量
int length; //顺序表的当前长度
}SeqList;
void InitList(SeqList &L);
void IncreaseSize(SeqList &L,int len);
void InitList(SeqList &L)
{
//用malloc函数申请一片连续的存储空间
L.data = (int*)malloc(sizeof(int) * InitSize);
L.MaxSize = InitSize;
L.length = 0;
}
void IncreaseSize(SeqList &L,int len)
{
int *p = L.data;
L.data = (int*)malloc(sizeof(int) * (InitSize+len));
for(int i=0;i<L.length;i++)
{
L.data[i] = p[i];
}
L.MaxSize = L.MaxSize + len;
free(p);
}
int main()
{
SeqList L;
InitList(L); //初始化顺序表
IncreaseSize(L, 5); //顺序表最大长度+5
return 0;
}
顺序表的动态分配实现
最新推荐文章于 2021-09-02 16:28:20 发布