From eb9717bb184cdaf0088981c4863b051f74ac0c03 Mon Sep 17 00:00:00 2001 From: Y-syntax Date: Wed, 9 Apr 2025 20:06:33 +0530 Subject: [PATCH] Overhaul list.c with dynamic array, add basic tests --- list.c | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ main.c | 13 +++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 list.c create mode 100644 main.c diff --git a/list.c b/list.c new file mode 100644 index 0000000000..2260e5b5f2 --- /dev/null +++ b/list.c @@ -0,0 +1,60 @@ +#include +#include + +typedef struct { + int*data; + int size; + int capacity; +} List; + +void list_init(List*l){ + l->capacity=4; + l->size=0; + l->data=malloc(sizeof(int)*l->capacity); +} + +void list_resize(List*l){ + l->capacity*=2; + l->data=realloc(l->data,sizeof(int)*l->capacity); +} + +void list_append(List*l,int value){ + if(l->size==l->capacity) + list_resize(l); + l->data[l->size++]=value; +} + +void list_insert(List*l,int index,int value){ + if(index<0||index>l->size)return; + if(l->size==l->capacity) + list_resize(l); + for(int i=l->size;i>index;--i) + l->data[i]=l->data[i-1]; + l->data[index]=value; + l->size++; +} + +void list_delete(List*l,int index){ + if(index<0||index>=l->size)return; + for(int i=index;isize-1;++i) + l->data[i]=l->data[i+1]; + l->size--; +} + +int list_get(List*l,int index){ + if(index<0||index>=l->size)return -1; + return l->data[index]; +} + +void list_print(List*l){ + for(int i=0;isize;++i) + printf("%d ",l->data[i]); + printf("\n"); +} + +void list_free(List*l){ + free(l->data); + l->data=NULL; + l->size=0; + l->capacity=0; +} diff --git a/main.c b/main.c new file mode 100644 index 0000000000..ae229fef33 --- /dev/null +++ b/main.c @@ -0,0 +1,13 @@ +#include "list.c" + +int main(){ + List l; + list_init(&l); + list_append(&l,10); + list_append(&l,20); + list_insert(&l,1,15); // 10 15 20 + list_delete(&l,0); // 15 20 + list_print(&l); + list_free(&l); + return 0; +}