1.先定义一个结构体
#define MaxSize 20
typedef int ElemType;
struct SqList{
ElemType data[MaxSize];
int length;
};
typedef struct SqList ArrayList;
2.插入
bool ListInsert(ArrayList &L,ElemType value,int place){
if(place<1||place>L.length+1||L.length+1>MaxSize){
return false;
}
for(int j=L.length;j>=place;j--){
L.data[j]=L.data[j-1];
}
L.data[place-1]=value;
L.length++;
return true;
}
3.删除
bool ListDelete(ArrayList &L,int place){
if(place<1||place>L.length+1||L.length+1>MaxSize){
return false;
}
for(int i=place-1;i<=L.length-1;i++){
L.data[i]=L.data[i+1];
}
L.length--;
return false;
}
4.完整代码
#include<stdio.h>
#define MaxSize 20
typedef int ElemType;
struct SqList{
ElemType data[MaxSize];
int length;
};
typedef struct SqList ArrayList;
bool ListInsert(ArrayList &L,ElemType value,int place){
if(place<1||place>L.length+1||L.length+1>MaxSize){
return false;
}
for(int j=L.length;j>=place;j--){
L.data[j]=L.data[j-1];
}
L.data[place-1]=value;
L.length++;
return true;
}
bool ListDelete(ArrayList &L,int place){
if(place<1||place>L.length+1||L.length+1>MaxSize){
return false;
}
for(int i=place-1;i<=L.length-1;i++){
L.data[i]=L.data[i+1];
}
L.length--;
return false;
}
void print(ArrayList &L){
for(int i=0;i<=L.length-1;i++){
printf("%d\t",L.data[i]);
}
}
int main(){
ArrayList L;
ListInsert(L,10,1);
ListInsert(L,9,2);
ListDelete(L,2);
print(L);
printf("%d\t",L.length);
}