/*
九大基本操作(不同的存储结构实现的代码不同)
此处用一维数组的动态分配:
InitList(&L);//初始化表,
Length(L);
LocateElem(L,e);
GetElem(L,i);
ListInsert(&L,i,e);
ListDelete(&L,i,&e);
PrintList(L);
Empty(L);
DestoryList(&L);
*/
/*静态分配的结构
#define MaxSize 50
typedef struct{
int data[MaxSize];
int length;
}SqList;
*/
#include<cstdio>
#include<cstdlib>
#include<cmath>
#define InitSize 100//动态分配的结构
#define AddSize 20//增加的空间个数
typedef struct{
int* data;
int MaxSize,length;//数组的最大容量,当前个数
}SeqList;
SeqList* InitList(SeqList &L){
L.data = (int*)malloc(sizeof(int)*InitSize);
if(L.data == NULL) return NULL;
L.MaxSize = InitSize;
L.length = 0;
return &L;
}
int Length(SeqList L){
return L.length;
}
int LocateElem(SeqList L,int e){//返回e在数组中的下标
int i = 0;
while(i<=L.length&&L.data[i] != e){
i++;
}
if(i>L.length){
exit(EXIT_FAILURE);
}
return i;
}
int GetElem(SeqList L,int i){//获取第i个元素
if(i<1||i>L.length+1) exit(EXIT_FAILURE);
return L.data[i-1];
}
SeqList* ListInsert(SeqList &L,int i,int e){//在第i个位置插入
if(i<1||i>L.length+1) exit(EXIT_FAILURE);
if(L.length >= L.MaxSize) {
L.data = (int*)realloc(L.data,sizeof(int)*(InitSize+AddSize));
if(L.data == NULL) exit(OVERFLOW);
L.MaxSize = InitSize+AddSize;
}
for(int j = L.length-1;j>=i-1;j--)
L.data[j+1] = L.data[i];
L.data[i-1] = e;
++L.length;
return &L;
}
SeqList* ListDelete(SeqList &L,int i,int &e){//删除第i个元素的位置
if(i<1||i>L.length) exit(EXIT_FAILURE);
e = L.data[i-1];
for(int j=i-1;j<L.length-1;j++)
L.data[j]=L.data[j+1];
--L.length;
return &L;
}
void PrintList(SeqList L){
int i = 0;
while(i<L.length){
printf("%d ",L.data[i]);
}
printf("\n");
}
bool Empty(SeqList L){
if(L.length == 0) return true;
else return false;
}
bool DestoryList(SeqLisrt &L){
for(int i=0;i<L.length;i++)
free(L);
}
main(){
SeqList SL;
SeqList* L = InitList(SL);
printf("%d",L);
return 0;
}