Dynamic Array List

Declare struct Dynamic Array List

typedef struct DynamicArrayList{
	int *arr;
	int capacity;
	int size;
}DynamicArrayList;
Dynamic Array List

function initialize DynamicArrayList

void init(DynamicArrayList *l, int capacity){
	l->capacity = capacity;
	l->arr = (int*)malloc(sizeof(int) * capacity);
	l->size = 0;
}
Dynamic Array List

function freeArrayList DynamicArrayList

void freeArrayList(DynamicArrayList *l){
	free(l->arr);
}
Dynamic Array List

function isEmpty DynamicArrayList

bool isEmpty(const DynamicArrayList *l){
	return l->size == 0;
}
Dynamic Array List

function resize DynamicArrayList

void resize(DynamicArrayList *l){
	if (l->size == l->capacity){
		l->capacity *= 2;
		l->arr = (int*)realloc(l->arr, sizeof(int) * l->capacity);
	}
}
Dynamic Array List

function addTail DynamicArrayList

void addTail(DynamicArrayList* l, int x){
	resize(l);
	l->arr[l->size++] = x;
}
Dynamic Array List

function output DynamicArrayList

void output(const DynamicArrayList *l){
	for (int i = 0; i < l->size; ++i){
		printf("%d ", l->arr[i]);
	}
	printf("\n");
}
Dynamic Array List

function insert DynamicArrayList

bool insert(DynamicArrayList *l, int k, int x){
	if (k < 0 || k > l->size){
		return false;
	}
	resize(l);
	for (int i = l->size++; i > k; --i){
		l->arr[i] = l->arr[i - 1];
	}
	l->arr[k] = x;
}