From 93d516c2d924eef5aafd5249ae49a7f9f0586970 Mon Sep 17 00:00:00 2001 From: kdeng00 Date: Thu, 25 Jul 2019 21:12:28 -0400 Subject: [PATCH] Added functionality to retrieve element from a list with the index --- include/klist.h | 2 ++ src/klist.c | 25 +++++++++++++++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/include/klist.h b/include/klist.h index 67228cb..3bbb0a7 100644 --- a/include/klist.h +++ b/include/klist.h @@ -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**); diff --git a/src/klist.c b/src/klist.c index c377f8e..8e6753f 100644 --- a/src/klist.c +++ b/src/klist.c @@ -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;