Following this reference, below is the list abstraction implementation using array,
/* list.h */
/*
List is an ordered collection(sequence) of homogeneous type elements(unique or duplicate).
By definition, List is not suppose to have collection of heterogeneous type elements.
All elements in a List are related.
List is mutable
Each element has a position.
If an element is deleted, then still the remaining elements sit in new order.
Array implementation of List
*/
#include<stddef.h>
#include<stdlib.h>
#include<string.h>
#define INITIAL_LIST_SIZE 50
#define NEW_LIST 0
#define DOUBLE_THE_LIST 1
#define HALF_THE_LIST 2
typedef struct List{
int *array;
int lastItemPosition;
int size;
}List;
extern List *arrayList;
void insertItem(int newItem, int location);
List* createList(List *, int);
/* arrayImpl.c */
#include"list.h"
List *createList(List *list, int flag){
List *lptr = (List *)malloc(sizeof(List));
if(flag == NEW_LIST){
lptr->array = malloc(INITIAL_LIST_SIZE*sizeof(int));
lptr->array = memset(lptr->array, -1, INITIAL_LIST_SIZE*sizeof(int));
lptr->lastItemPosition = -1;
lptr->size = INITIAL_LIST_SIZE;
}else if(flag == DOUBLE_THE_LIST){
lptr->array = malloc(2*(list->size)*sizeof(int));
lptr->array = memcpy(lptr->array, list->array, list->size*sizeof(int));
lptr->lastItemPosition = list->lastItemPosition;;
lptr->size = 2*(list->size);
}else if(flag == HALF_THE_LIST){
lptr->array = malloc(((list->size)/2)*sizeof(int));
lptr->array = memcpy(lptr->array, list->array, (list->size/2)*sizeof(int));
lptr->lastItemPosition = list->lastItemPosition;;
lptr->size = (list->size)/2;
}
return lptr;
}
void insertItem(int newItem, int index){
/* House keeping */
if(arrayList->lastItemPosition + 1 == arrayList->size){
arrayList = createList(arrayList, DOUBLE_THE_LIST);
}
/* Insert the element */
arrayList->array[index] = newItem;
if(index > arrayList->lastItemPosition){
arrayList->lastItemPosition = index;
}
return;
}
void deleteItem(int index){
arrayList->array[index] = -1;
if(index == arrayList->lastItemPosition){
arrayList->lastItemPosition--;
}
/* House keeping */
if(arrayList->size > INITIAL_LIST_SIZE){
if(arrayList->lastItemPosition == ((arrayList->size)/2)){
arrayList = createList(arrayList, HALF_THE_LIST);
arrayList = createList(arrayList, HALF_THE_LIST);
}
}
}
/* main .c */
#include"list.h"
List *arrayList = NULL;
int main(void){
arrayList = createList((List *)NULL, NEW_LIST);
}
Is List
following abstraction and encapsulation?
Note: Encapsulation is about maintaining in-variants of ADT, after performing operations on ADT. Abstraction is a barrier between representation and usage.
arrayList
global, and not an arbitraryList
pointer. \$\endgroup\$