实现顺序表的各种基本算法

编写一个程序实现以下功能:

头文件

#include 
#include 
#include 
typedef int ElemType;

1.初始化顺序表L

2.依次插入a,b,c,d,e元素

void CreateList(List * L,ElemType a[],int n){
    int i = 0,k = 0;
    while (i < n){
        L -> data[k] = a[i];
        k++; i++;
    }
    L -> length = k;
}

3.输出顺序表元素及其长度

void DisList(List * L){
    printf("输出线性表:\n");
    for (int i = 0; i < L -> length; ++i) {
        printf("%c  ",L -> data[i]);
    }
    printf("\n元素个数为:%d\n",L -> length);
}

4.判断顺序表是否为空

bool EmptyList(List * L){
    if(L -> length)
        printf("顺序表不为空\n");
    else
        printf("顺序表空的\n");
    return L -> length;
}

5.输出顺序表第3个元素

bool GetListR(List * L,int i,ElemType x){
    if(i <= 0 || i > L -> length) return false;
    i--;
    x = L -> data[i];
    printf("第%d个是%c\n",i + 1,x);
    return true;
}

6.输出a的位置

void GetListF(List * L,ElemType x){
    int i = 0;
    while (i < L -> length && L -> data[i] != x){
        i++;
    }
    if(i == L -> length)
        printf("%c不存在",x);
    else{
        i++;
        printf("%c在第%d位\n",x,i);
    }
}

 7.在第4个位置上插入f

bool InsertList(List * L,int i,ElemType x){
    if(i <= 0 || i > L -> length){
        printf("位置不合法\n");
        return false;
    }
    i--;
    int j = L -> length;
    while (j > i){
        L -> data[j] = L -> data[j - 1];
        j--;
    }
    L -> data[i] = x;
    L -> length++;
    printf("%c插入成功\n",x);
    return true;
}

8.输出顺序表L

9.删除顺序表L的第3个元素

bool DeleteList(List * L,int i,ElemType x){
    if(i <= 0 || i > L -> length){
        printf("位置不合法\n");
        return false;
    }
    int j = i;
    i--;
    x = L -> data[i];
    while (j < L -> length){
        L -> data[j - 1] = L -> data[j];
        j++;
    }
    L -> length--;
    printf("第%d位元素是%c,删除成功\n",i+ 1,x);
    return true;
}

 10.输出并释放顺序表L

void DestroyList(List * L){
    printf("销毁成功\n");
    free(L);
}

 主函数:

int main(){
    List *L;
    L = (List * ) malloc(sizeof(List));
    L -> length = 0;
    ElemType ch[5] = {'a','b','c','d','e'};
    printf("插入对应元素:\n");
    CreateList(L,ch,5);
    DisList(L);
    EmptyList(L);
    ElemType x;
    GetListR(L,3,x);
    GetListF(L,'a');
    InsertList(L,5,'f');
    DisList(L);
    DeleteList(L,3,x);
    DisList(L);
    DestroyList(L);
}

你可能感兴趣的:(数据结构,算法,数据结构,c语言)