顺序表的基本操作

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 20

struct SeqList{
    int data[MAXSIZE];
    int len;
};

SeqList * initSeqList(){
    SeqList * L;
    L = (SeqList*)malloc(sizeof(SeqList));
    L->len = 0;
    return L;
}

void createSeqList(SeqList * L){
    int n;
    printf("please input the length of the list!\n");
    scanf("%d",&n);
    printf("please input the elements of the list!\n");
    for(int i=1;i<=n;i++){
        scanf("%d,",&L->data[i]);
    }
    L->len = n;
}

void traverseSeqList(SeqList * L){
    printf("the elements of the list are:\n");
    for(int i=1;i<=L->len;i++){
        printf("%d ",L->data[i]);
    }
}

void insertSeqList(SeqList * L,int i,int x){
    if(L->len == MAXSIZE){
        printf("the list is full!\n");
    }else if(i<1 || i>L->len+1){
        printf("the location is invalid!\n");
    }else{
        for(int j=L->len;j>=i;j--){
            L->data[j+1] = L->data[j];
        }
        L->data[i] = x;
        L->len++;
    }
}

void delSeqList(SeqList * L,int i){
    if(L->len == 0){
        printf("the list is empty!\n");
    }else if(i<1 || i>L->len){
        printf("the location is invalid!\n");
    }else{
        for(int j=i;j<=L->len;j++){
            L->data[j] = L->data[j+1];
        }
        L->len--;
    }
}

void reverseSeqList(SeqList * L){
    int temp;
    for(int i=1;i<=(L->len)/2;i++){
        temp = L->data[i];
        L->data[i] = L->data[L->len-i+1];
        L->data[L->len-i+1] = temp;
    }
}

int main(){
    SeqList * L;
    L = initSeqList();

    createSeqList(L);
    printf("\n");
    traverseSeqList(L);
    printf("\n");

    insertSeqList(L,3,521);
    printf("after insert:\n");
    traverseSeqList(L);
    printf("\n");

    delSeqList(L,1);
    printf("after delete:\n");
    traverseSeqList(L);
    printf("\n");

    reverseSeqList(L);
    printf("after reverse\n");
    traverseSeqList(L);
    printf("\n");

    return 0;
}

你可能感兴趣的:(顺序表的基本操作)