顺序表

2021-03-20  本文已影响0人  qianranow

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

#define InitSize 10

typedef struct {
    int *data;
    int length;
    int maxSize;
} SqList;

int InitList(SqList *l) {
    int *data = (int *)malloc(InitSize*sizeof(int));
    if (data == NULL) return -1;
    l->data = data;
    l->length = 0;
    l->maxSize = InitSize;
    return 1;
}

int IncreaseSize(SqList *l, int len) {
    int *p = l->data;
    int *data = (int *)malloc((l->maxSize+len)*sizeof(int));
    if (data == NULL) return -1;
    for (int i = 0; i < l->maxSize; i++) {
        data[i] = p[i];
    }
    l->data = data;
    l->maxSize += len;
    free(p);
    return 1;
}

int ListInsert(SqList *l, int i, int e) {
    if (l->length == l->maxSize) return -1;
    if (i < 1 || i > l->length + 1) return -1;
    for (int j = l->length; j >= i; j--) {
        l->data[j] = l->data[j-1];
    }
    l->data[i-1] = e;
    l->length++;
    return 1;
}

int ListDelete(SqList *l, int i, int *e) {
    if (l->length == 0) return -1;
    if (i < 1 || i > l->length) return -1;
    *e = l->data[i-1];
    for (int j = i; j < l->length; j++) {
        l->data[j-1] = l->data[j];
    }
    l->length--;
    return 1;
}

int GetElem(SqList *l, int i) {
    if (i < 1 || i > l->length) return -1;
    return l->data[i-1];
}

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

int Length(SqList l) {
    return l.length;
}

void ListPrintf(SqList l) {
    for (int i = 0; i < l.length; i++) {
        printf("%i\n", l.data[i]);
    }
}

int Empty(SqList l) {
    return l.length == 0 ? 1 : -1;
}

void DestroyList(SqList *l) {
    free(l->data);
    l->data = NULL;
    l->length = 0;
    l->maxSize = 0;
}

// 分割线
void Sep() {
    printf("**************\n");
}

int main() {
    SqList l;
    InitList(&l);
    ListInsert(&l, 1, 1);
    ListInsert(&l,2, 12);
    ListInsert(&l,1, 13);
    ListPrintf(l);
    Sep();
    int e = -1;
    ListDelete(&l, 1, &e);
    printf("%i\n", e);
    Sep();
    ListPrintf(l);
    Sep();
    printf("%i\n", GetElem(&l, 2));
    printf("%i\n", LocateElem(&l, 1));
    printf("%i\n", Length(l));
    Sep();
    DestroyList(&l);
    printf("%p\n", l.data);
    printf("%i\n", Empty(l));
    return 0;
}

上一篇下一篇

猜你喜欢

热点阅读