代码实现
#include <stdio.h>
#include <malloc.h>
#define InitSize 10
typedef struct{
int *data;
int MaxSize;
int length; // 当前长度
}SqList;
// 初始化
void InitList(SqList* L){
L->data=(int *)malloc(InitSize*sizeof(int));
L->length=0;
L->MaxSize=InitSize;
}
// 动态增加
void IncreaseSize(SqList * L,int len) {
int *p = L->data;
L->data = (int *) malloc((L->MaxSize + len) * sizeof(int));
for (int i = 0; i < L->length; i++) {
L->data[i] = p[i];
}
L->MaxSize = L->MaxSize + len;
free(p);
}
/// 插入一条数据
int insert(SqList* L ,int data){
// 有空间的话
if(L->length<L->MaxSize){
L->data[L->length++] = data;
return 0;
}
return -1;
}
int main(){
SqList L;
InitList(&L);
printf("Max len= %d",L.MaxSize);
printf("\n");
printf("length = %d",L.length);
for (int i = 0; i < 5; ++i) {
insert(&L,i);
}
printf("\n");
printf("Inserted Date is : \n");
for (int i = 0; i < L.length; ++i) {
printf("%d ",L.data[i]);
}
printf("\n");
printf("Max len= %d",L.MaxSize);
printf("\n");
printf("length = %d",L.length);
IncreaseSize(&L,5);
printf("\n After Increase the Sql Size \n");
printf("Max len= %d",L.MaxSize);
printf("\n");
printf("length = %d",L.length);
printf("\n");
printf("Inserted Date is : \n");
for (int i = 0; i < L.length; ++i) {
printf("%d ",L.data[i]);
}
return 0;
};
运行结果如下
Max len= 10 length = 0 Inserted Date is : 0 1 2 3 4 Max len= 10 length = 5 After Increase the Sql Size Max len= 15 length = 5 Inserted Date is : 0 1 2 3 4