c语言实现vector及其相关函数(自存)

#include<stdio.h>
#include <stdlib.h> 
#define PREALLOC_MAX 1024
#define DEFAULT_CAPACITY 8

typedef int E;

typedef struct {
    E* elements;   // 指向堆空间的数组
    int size;    // 元素的个数
    int capacity; // 数组的容量
} Vector;

void push_back(Vector* v, E val);
// 在数组最前面添加元素,所有元素依次后移
void push_front(Vector* v, E val);
// 删除最后一个元素, 并把最后一个元素返回
E pop_back(Vector* v);
// 删除第一个元素,并把第一个元素返回
E pop_front(Vector* v);
void grow_capacity(Vector* v);
Vector* vector_create(void);

int main(void){
    // Vector v1;
    Vector* v = vector_create();
   /* push_back(v, 1);
    push_back(v, 2);
    push_back(v, 3);*/
    push_front(v, 1);
    push_front(v, 2);
    push_front(v, 3);
    int pb = pop_front(v);
    printf("%d", pb);
    return 0;
}

void grow_capacity(Vector* v) {
    int new_capacity = v->capacity < PREALLOC_MAX ? v->capacity << 1 : v->capacity + PREALLOC_MAX;
    E* p = realloc(v->elements, new_capacity * sizeof(E));
    if (!p) {
        printf("ERROR:REALLOC FAILED IN REALLOC\n");
        exit(1);
    }
    v->elements = p;
    v->capacity = new_capacity;
}

Vector* vector_create(void) {
    Vector* v = malloc(sizeof(Vector));
    if (!v) {
        printf("Error: malloc failed in vector_create\n");
        exit(1);
    }
    E* p = malloc(DEFAULT_CAPACITY * sizeof(E));
    if (!p) {
        free(v);
        printf("Error: malloc failed in vector_create\n");
        exit(1);
    }
    v->elements = p;
    v->size = 0;
    v->capacity = DEFAULT_CAPACITY;
    return v;
}
void vector_destroy(Vector* v) {
    free(v->elements);
    free(v);
}

void push_back(Vector* v, E val) {
    //判断是否需要扩容
    if (v->size == v->capacity) {
        grow_capacity(v);
    }
    v->elements[v->size++] = val;
}

void push_front(Vector* v, E val) {
    //判断是否需要扩容
    if (v->size == v->capacity) {
        grow_capacity(v);
    }
    //把元素往后移动一位
    for (int i = v->size - 1; i >= 0; i--)
        v->elements[i+1] = v->elements[i];
    //在数组最前面添加元素
    v->elements[0] = val;
    v->size++;
}

E pop_back(Vector* v){
    //判断是否为空
    if (v->size == 0)
    {
        printf("error:vector size is %d!!!!", v->size);
        return -1;
    }
    //返回最后一个元素
    int latter = v->elements[v->size - 1];
    v->size--;
    return latter;
}
E pop_front(Vector* v) {
    //判断是否为空
    if (v->size == 0)
    {
        printf("error:vector size is %d!!!!", v->size);
        return -1;
    }
    int val = v->elements[0];
    for (int i = 1; i < v->size; i++)
    {
        v->elements[i-1] = v->elements[i];
    }
    v->size--;
    return val;
}

 

posted @ 2024-05-02 20:54  Uiney  阅读(2)  评论(0编辑  收藏  举报