数据结构---顺序表

2017-04-15  本文已影响0人  Bean_Nan

插入,删除,扩容,清空内存

#include <stdio.h>
#include <malloc.h>

#define OK 1
#define ERROR 0

typedef struct Vector {
    int size, length;
    int *data;
}Vector;

void init (Vector *vector, int size) {
    vector->size = size;
    vector->length = 0;
    vector->data = (int *)malloc(sizeof(int) * size);
}

int insert(Vector *vector, int loc, int value) {
    if (loc < 0 || loc > vector->length) {
        return ERROR;
    }
    if (vector->length >= vector->size) {
        expand(vector);
    }
    for (int i = vector->length; i > loc; i--) {
        vector->data[i] = vector->data[i - 1];
    }
    vector->data[loc] = value;
    vector->length++;

    return OK;
}

int delete(Vector *vector, int index) {
    if (index < 0 || index >= vector->length) {
        return ERROR;
    }
    for (int i = index; i < vector->length; i++) {
        vector->data[i - 1] = vector->data[i];
    }
    vector->length--;

    return OK;
}

void expand(Vector *vector) {
    int *old_data = vector->data;
    vector->size = vector->size * 2;
    vector->data = (int *)malloc(sizeof(int) * vector->size);

    for (int i = 0; i < vector->length; i++) {
        vector->data[i] = old_data[i];
    }

    free(old_data);
}

void clear(Vector *vector) {
    free(vector->data);
    free(vector);
}

int main() {
    printf("Hello, World!\n");
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读