Added functionality to retrieve element from a list with the index

This commit is contained in:
kdeng00
2019-07-25 21:12:28 -04:00
parent fed1c1a091
commit 93d516c2d9
2 changed files with 25 additions and 2 deletions
+2
View File
@@ -2,6 +2,8 @@
struct node* init_list(void*, size_t);
void* list_element_at(struct node*, int);
int is_list_init(struct node**);
int list_size(struct node**);
+23 -2
View File
@@ -15,6 +15,28 @@ struct node* init_list(void *val, size_t val_size)
return list;
}
void* list_element_at(struct node *list, int index)
{
if (index < 0)
return NULL;
int size_of_list = list_size(&list);
if (index >= size_of_list)
return NULL;
struct node *tmp = NULL;
for (int i = 0; i <= index; ++i) {
tmp = list;
list = list->next;
if (i == index)
return tmp->data;
}
return NULL;
}
int is_list_init(struct node **list)
{
if (*list == NULL)
@@ -107,8 +129,7 @@ void traverse(struct node *list, void (*print_val)(struct node*))
struct node *tmp;
do
{
do {
(*print_val)(list);
tmp = list;
list = list->next;