Made the list implementation more generic to hold various types, includung structs. Updated traversing function that accepts a function pointer that contains the logic to print element in the list

This commit is contained in:
amazing-username
2019-07-23 21:07:50 -04:00
parent 729f87fee0
commit d96758277a
2 changed files with 18 additions and 12 deletions
+3 -3
View File
@@ -1,10 +1,10 @@
#include "types.h" #include "types.h"
struct node* init_list(void*); struct node* init_list(void*, size_t);
int is_list_init(struct node**); int is_list_init(struct node**);
void insert_at_begin(struct node**, void*); void insert_at_begin(struct node**, void*, size_t);
void insert_at_end(struct node**, void*); void insert_at_end(struct node**, void*, size_t);
void free_list(struct node**); void free_list(struct node**);
void traverse(struct node*, void (*)(struct node*)); void traverse(struct node*, void (*)(struct node*));
+15 -9
View File
@@ -4,11 +4,11 @@
#include "klist.h" #include "klist.h"
struct node* init_list(void *val) struct node* init_list(void *val, size_t val_size)
{ {
struct node *list = (struct node*)malloc(sizeof(struct node)); struct node *list = (struct node*)malloc(sizeof(struct node));
void *tmp_val = (void*)malloc(sizeof(val)); void *tmp_val = (void*)malloc(val_size);
memcpy(tmp_val, val, sizeof(val)); memcpy(tmp_val, val, val_size);
list->data = tmp_val; list->data = tmp_val;
list->next = NULL; list->next = NULL;
@@ -23,11 +23,11 @@ int is_list_init(struct node **list)
return 0; return 0;
} }
void insert_at_begin(struct node **list, void *val) void insert_at_begin(struct node **list, void *val, size_t val_size)
{ {
struct node *tmp = (struct node*)malloc(sizeof(struct node)); struct node *tmp = (struct node*)malloc(sizeof(struct node));
void *tmp_val = (void*)malloc(sizeof(val)); void *tmp_val = (void*)malloc(val_size);
memcpy(tmp_val, val, sizeof(val)); memcpy(tmp_val, val, val_size);
if ((*list) == NULL) { if ((*list) == NULL) {
(*list) = tmp; (*list) = tmp;
@@ -40,11 +40,11 @@ void insert_at_begin(struct node **list, void *val)
tmp->next = *list; tmp->next = *list;
*list = tmp; *list = tmp;
} }
void insert_at_end(struct node **list, void *val) void insert_at_end(struct node **list, void *val, size_t val_size)
{ {
struct node *tmp = (struct node*)malloc(sizeof(struct node)); struct node *tmp = (struct node*)malloc(sizeof(struct node));
void *tmp_val = (void*)malloc(sizeof(val)); void *tmp_val = (void*)malloc(val_size);
memcpy(tmp_val, val, sizeof(val)); memcpy(tmp_val, val, val_size);
if ((*list) == NULL) { if ((*list) == NULL) {
(*list) = tmp; (*list) = tmp;
@@ -66,11 +66,17 @@ void free_list(struct node **list)
struct node *t = NULL; struct node *t = NULL;
struct node *l = *list; struct node *l = *list;
if (l == NULL)
return;
do { do {
t = l; t = l;
l = l->next; l = l->next;
free(t); free(t);
t = NULL; t = NULL;
if (l == NULL)
return;
} }
while (l->next != NULL); while (l->next != NULL);