2020-05-29 23:23:24 +03:00
|
|
|
#include "list.h"
|
2019-07-07 23:20:11 +03:00
|
|
|
#include <assert.h>
|
2020-05-29 23:23:24 +03:00
|
|
|
#include <stdarg.h>
|
2019-07-07 23:20:11 +03:00
|
|
|
#include <stddef.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
|
|
|
#define L List_T
|
|
|
|
|
|
|
|
/* Initial list */
|
2020-05-29 23:23:24 +03:00
|
|
|
L List_init(void)
|
|
|
|
{
|
2019-07-07 23:20:11 +03:00
|
|
|
L list;
|
2020-05-29 23:23:24 +03:00
|
|
|
list = (L)malloc(sizeof(L));
|
2019-07-07 23:20:11 +03:00
|
|
|
list->next = NULL;
|
|
|
|
return list;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Push an element into top of the list */
|
2020-05-29 23:23:24 +03:00
|
|
|
L List_push(L list, void *val)
|
|
|
|
{
|
2019-07-07 23:20:11 +03:00
|
|
|
L new_elem = (L)malloc(sizeof(L));
|
|
|
|
new_elem->val = val;
|
|
|
|
new_elem->next = list;
|
|
|
|
return new_elem;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Length of list */
|
2020-05-29 23:23:24 +03:00
|
|
|
int List_length(L list)
|
|
|
|
{
|
2019-07-07 23:20:11 +03:00
|
|
|
int n;
|
2020-06-28 18:25:37 +03:00
|
|
|
for (n = 0; list; list = list->next) n++;
|
2023-06-21 00:07:09 +03:00
|
|
|
return n - 1;
|
2019-07-07 23:20:11 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
/* Convert list to array */
|
2020-05-29 23:23:24 +03:00
|
|
|
void **List_toArray(L list)
|
|
|
|
{
|
2023-06-21 00:07:09 +03:00
|
|
|
int i, n = List_length(list) + 1;
|
2020-05-29 23:23:24 +03:00
|
|
|
void **array = (void **)malloc((n + 1) * sizeof(*array));
|
2019-07-07 23:20:11 +03:00
|
|
|
|
2020-05-29 23:23:24 +03:00
|
|
|
for (i = 0; i < n; i++)
|
|
|
|
{
|
2019-07-07 23:20:11 +03:00
|
|
|
array[i] = list->val;
|
|
|
|
list = list->next;
|
|
|
|
}
|
|
|
|
array[i] = NULL;
|
|
|
|
return array;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Create and return a list */
|
2020-05-29 23:23:24 +03:00
|
|
|
L List_list(L list, void *val, ...)
|
|
|
|
{
|
2019-07-07 23:20:11 +03:00
|
|
|
va_list ap;
|
|
|
|
L *p = &list;
|
|
|
|
|
|
|
|
va_start(ap, val);
|
2020-05-29 23:23:24 +03:00
|
|
|
for (; val; val = va_arg(ap, void *))
|
|
|
|
{
|
2019-07-07 23:20:11 +03:00
|
|
|
*p = malloc(sizeof(L));
|
|
|
|
(*p)->val = val;
|
|
|
|
p = &(*p)->next;
|
|
|
|
}
|
|
|
|
*p = NULL;
|
|
|
|
va_end(ap);
|
|
|
|
return list;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Append 2 lists together */
|
2020-05-29 23:23:24 +03:00
|
|
|
L List_append(L list, L tail)
|
|
|
|
{
|
2019-07-07 23:20:11 +03:00
|
|
|
L *p = &list;
|
2020-05-29 23:23:24 +03:00
|
|
|
while ((*p)->next)
|
|
|
|
{
|
2019-07-07 23:20:11 +03:00
|
|
|
p = &(*p)->next;
|
|
|
|
}
|
|
|
|
|
|
|
|
*p = tail;
|
|
|
|
return list;
|
|
|
|
}
|