动态分配顺序表

#include 
#include 

#define MaxSize 10
typedef struct {
    char name[20];
}ElemType;
typedef struct {
    ElemType data[MaxSize];
    int length;
}SqList;
void InitList(SqList *L);
void show(SqList *L);
void enter(SqList *L);
bool ListInsert(SqList *L, int i, ElemType e);
bool ListDelete(SqList *L,int i,ElemType e);
ElemType GetElem(SqList *L, int i);
int LocateElem(SqList *L,ElemType e);
int main(){
    SqList q;
    SqList *L=&q;
    InitList(L);
    enter(L);
    show(L);
    ElemType temp={"jack"};
    ListInsert(L, 4, temp);
    show(L);
    ListDelete(L,2,temp);
    show(L);
    printf("%s\n",temp.name);
    printf("%s\n",GetElem(L,3).name);
    printf("%d\n",LocateElem(L,temp));
    return 0;

}


void InitList(SqList *L) {
    L->length=3;
}

void show(SqList *L){
    for (int i = 0; i < L->length; ++i) {
        printf("%s\n", L->data[i].name);
    }

}

void enter(SqList *L){
    for (int i = 0; i < L->length; ++i) {
        scanf("%s",L->data[i].name);
    }
}

bool ListInsert(SqList *L, int i, ElemType e){//这里的i是线性表中以1开始的顺序
    /*代码应该具有健壮性*/
    if(i<1||i>L->length+1)//判断i的范围是否有效
        return false;
    if(L->length>=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(SqList *L,int i,ElemType e){
    if(i<1||i>L->length+1){
        return false;
    }
    e=L->data[i-1];
    for (int j = i; j <= L->length;j++) {//集体前移,++
        L->data[j -1] = L->data[j];
    }
    L->length--;
    return true;

}

ElemType GetElem(SqList *L, int i){
    return L->data[i-1];
}

int LocateElem(SqList *L,ElemType e){
    for (int i = 0; i < L->length; ++i) {
        if(strcmp(L->data[i].name,e.name)==0)
            return i+1;
    }
    return 0;
}

 

你可能感兴趣的:(笔记)