bool alAddAt(ArrayList *list, int data, int index) {
    if (list == NULL) {
        perror("Cannot add data to a null list.");
        return false;
    }
    if (list->size < list->capacity) {
        if (index > list->size) {
            perror("Cannot add data to size + 1 index.");
            return false;
        }
        else if (index == list->size) { // Normal add to end
            list->data[list->size] = data;
        }
        else { // Adding in the middle
            // We need to shift everything down
            for (int i = list->size; i > index; i--) {
                list->data[i] = list->data[i - 1];
            }
            // Set the new value
            list->data[index] = data;
        }
        list->size++;
    }
    else {
        bool worked = doubleCapacity(list);
        if (!worked)
            return false;
        return alAddAt(list, data, index);
    }
    return true;
}
Ejemplo n.º 2
0
void Vector<elementType>::push_back(elementType element)
{
    if(vectorSize >= capacity)
    {
        elements = doubleCapacity(elements, capacity);
        capacity = capacity*2;
    }
    elements[vectorSize] = element;
    vectorSize++;
}