Skip to content

Instantly share code, notes, and snippets.

@rlapz
Last active August 7, 2021 13:25
Show Gist options
  • Save rlapz/a6a643c1e9197389093bc74010c7f7b7 to your computer and use it in GitHub Desktop.
Save rlapz/a6a643c1e9197389093bc74010c7f7b7 to your computer and use it in GitHub Desktop.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* WARNING!
*
* Horrible linked list :p
*/
/* macros */
struct List {
void *value;
struct List *next;
};
#define FOREACH(out, in) \
for (struct List *out = in; out->next != NULL; out = out->next)
/* function prototypes */
static struct List *init_list (void);
static int insert_list (struct List **list, void *data);
static void clear_list (struct List **list);
/* function implementations */
static struct List *
init_list(void)
{
struct List *l = malloc(sizeof(struct List));
if (l == NULL) {
perror("init_list()");
return NULL;
}
l->value = NULL;
l->next = NULL;
return l;
}
static int
insert_list(struct List **list, void *data)
{
if ((*list) == NULL) {
errno = EINVAL;
perror("insert_list()");
return -1;
}
struct List *new_l = malloc(sizeof(struct List));
if (new_l == NULL) {
perror("insert_list(): new");
return -1;
}
new_l->value = data;
new_l->next = (*list);
(*list) = new_l;
return 0;
}
static void
clear_list(struct List **list)
{
struct List *tmp = (*list);
struct List *next;
while (tmp != NULL) {
next = tmp->next;
free(tmp);
tmp = next;
}
(*list) = NULL;
}
int
main(void)
{
int arr[] = {10,2,4,5,6,21};
struct List *l = init_list();
/* array to linked list */
for (int i = 5; i >= 0; i--) {
if (insert_list(&l, (int*)&arr[i]) < 0)
goto clean;
}
FOREACH(out, l)
printf("%d\n", *(int*)out->value);
clean:
clear_list(&l);
return errno;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment