需要帮助在 C 中制作 ArrayList Add At

Need help making an ArrayList Add At in C

我不确定如何使用 arrlist_addat 在特定索引处添加到列表中。我包括了我的一些其他方法和我的结构,因此您可以看到我是如何做的。该方法必须 return 如果添加它,则为布尔值 true,如果失败则为 false。

感谢任何帮助,谢谢。

struct ArrayList {
    void** arr;
    int size;
    int maxSize;
    int itemSize;
    char* type;
};

struct ArrayList* arrlist_initialize(int maxSize, int itemSize, char* dataType) {
    struct ArrayList* list = malloc(sizeof(struct ArrayList));
    list->size = 0;
    list->maxSize = maxSize;
    list->itemSize = itemSize;
    list->type = dataType;
    list->arr = NULL;
    return list;
}

bool arrlist_add(struct ArrayList* list, void* element) {
    void** data = realloc(list->arr, sizeof(*list->arr));
    if (data == NULL)
        return false;
    data[list->size] = element;
    list->arr = data;
    list->size = list->size+1;
    return true;
}

bool arrlist_addat(struct ArrayList* list, int index, void* element) {

    //Need help here.

}

void* arrlist_get(struct ArrayList* list, int index) {
    void* value = list->arr[index];
    if (value != NULL)
        return value;
    return NULL;
}

int arrlist_index_of(struct ArrayList* list, void* element) {
    for (int i = 0; i < list->size; ++i) {
        if (element == arrlist_get(list, i))
            return i;
    }
    return -1;
}

假设数组的长度是maxSize,你只要在插入元素前将元素右移,像这样:

bool arrlist_addat(struct ArrayList* list, int index, void* element)
{
    bool done;
    int i;

    assert(list != NULL);
    
    if ((list->size < list->maxSize) && (index >= 0) && (index <= list->size)) {
        /*make room for the new element*/
        for (i = list->size; i > index; i--) {
            list->arr[i] = list->arr[i - 1];
        }
        
        list->arr[index] = element;     
        list->size++;
        done = true;
    } else {
        done = false;
    } 
    return done;    
}

规定的要求是 arrlist_addat 应在给定索引处插入一个不能大于当前大小的元素。所以在检查需求之后,函数只需要重新分配 array/list of void * 值的内存,将 void * 值从给定索引向上移动一个,然后设置将插入的 void * 值写入索引位置。

假设实现具有优化的 memmove 函数,这可能是调整现有元素的最快方法。这是一个示例实现:

bool arrlist_addat(struct ArrayList* list, int index, void* element) {
    void** data;
    if (index > list->size)
        return false;
    data = realloc(list->arr, sizeof(*list->arr) * (list->size + 1));
    if (!data)
        return false;
    memmove(&list->arr[index + 1], &list->arr[index], (list->size - index) * sizeof(*list->arr));
    list->arr[index] = element;
    list->size++;
    return true;
}

arrlist_add 可以使用 arrlist_addat:

来实现
bool arrlist_add(struct ArrayList* list, void* element) {
    return arrlist_addat(list, list->size, element);
}

旁白:arrlist_get 可能应该检查索引,return NULL 如果超出范围:

void* arrlist_get(struct ArrayList* list, int index) {
    if (index >= list->index)
        return NULL;
    // Should we also check for negative indices here?
    // It's probably better to use unsigned indices anyway!
    return list->arr[index];
}