#include<stdio.h>
#include<stdlib.h>
#define InitSize 5
typedef struct {
int* data;
int length;
int MaxSize;
}DynamicList;
//初始化
void InitList(DynamicList& L) {
L.data = (int*)malloc(InitSize * sizeof(int));
L.MaxSize = InitSize;
L.length = 0;
}
bool ListInsert(DynamicList& L, int i, int e) {
if (i<1 || i>L.length + 1|| L.length >= L.MaxSize) {
return false;
}
for (int j = L.length; j >= i; j--) {
L.data[j] = L.data[j - 1];
}
L.data[i - 1] = e;
L.length++;
return true;
}
bool ListDelete(DynamicList& L, int i, int& e) {
if (i<1 || i>L.length) {
return false;
}
e = L.data[i - 1];
for (i; i < L.length; i++) {
L.data[i - 1] = L.data[i];
}
L.length--;
return true;
}
void WriteOne(DynamicList& L, int num) {
for (int i = 0; i < num; i++) {
L.data[i] = i;
L.length++;
}
}
void print(DynamicList L) {
for (int i = 0; i < L.length; i++) {
printf("serial number %d content %d\n", i, L.data[i]);
}
}
int main() {
DynamicList L;
int e;
InitList(L);
WriteOne(L,4);
printf("Before insert\n");
print(L);
if (ListInsert(L, 3, 9))
printf("Insert successful\n");
else
printf("Insert fails\n");
printf("After insert\n");
print(L);
printf("Before delete\n");
print(L);
if (ListDelete(L, 3, e))
printf("Insert successful\n The deleted value is %d\n",e);
else
printf("Insert fails\n");
printf("After delete\n");
print(L);
return 0;
}