Something like this should work fine. Note that the definition of struct Node
never leaves List.c
.
list.h
#pragma once
#include <stdbool.h>
struct List {
struct Node *front;
};
void list_init(struct List **list);
void list_free(struct List *list);
void list_insert(struct List *list, void *value);
bool list_contains(struct List *list, void *value);
list.c
#include <stdbool.h>
#include <stdlib.h>
#include "list.h"
struct Node {
void *value;
struct Node *next;
};
void list_init(struct List **list) {
*list = malloc(sizeof(**list));
}
void list_free(struct List *list) {
struct Node *node = list->front;
while (node != NULL) {
struct Node *next = node->next;
free(node);
node = next;
}
free(list);
}
void list_insert(struct List *list, void *value) {
struct Node *node = malloc(sizeof(*node));
node->value = value;
node->next = list->front;
list->front = node;
}
bool list_contains(struct List *list, void *value) {
struct Node *node;
for (node = list->front; node != NULL; node = node->next)
if (node->value == value)
return true;
return false;
}
main.c
#include <stdio.h>
#include "list.h"
int main() {
struct List *l;
list_init(&l);
int *value_1 = malloc(sizeof(int));
int *value_2 = malloc(sizeof(int));
int *value_3 = malloc(sizeof(int));
list_insert(l, value_1);
list_insert(l, value_2);
list_insert(l, value_3);
printf("Does the list contain value_1: %d\n", list_contains(l, value_1));
printf("Does the list contain null: %d\n", list_contains(l, NULL));
list_free(l);
return 0;
}
It's very possible that I have some errors in this code. If you see any, feel free to fix them.