aboutsummaryrefslogtreecommitdiff
path: root/lib/list/list.c
blob: 753fdb159eec3795a5da8bb8469ab10d4453dc12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "list.h"
#include "../malloc/malloc.h"


list_node_t *__new_list_node(void *value);


list_t *new_list()
{
	list_t *list = malloc(sizeof(list_t));
	list->first = 0;
	list->last  = 0;
	list->size  = 0;
	return list;
}


list_t *from_array(void **array, u64 size)
{
	int i;
	list_t *list = new_list();
	list->size = size;

	for (i = 0; i < size; ++i)
		list_append(list, array[i]);
	
	return list;
}


void list_append(list_t *list, void *value)
{
	list_node_t *node = __new_list_node(value);

	if (list->last == 0) {
		list->first = node;
		list->last  = list->first;
	} else {
		list->last->next = node;
		node->previous = list->last;
		list->last = node;
	}

	++list->size;
}


void list_prepend(list_t *list, void *value)
{
	list_node_t *node = __new_list_node(value);

	if (list->last == 0) {
		list->first = node;
		list->last  = list->first;
	} else {
		list->first->previous = node;
		node->next = list->first;
		list->first = node;
	}

	++list->size;
}


void *pop_first(list_t *list)
{
	void *value = list->first->value;
	list_node_t *node = list->first;

	list->first = node->next;
	free(node);

	--list->size;
	return value;
}


void *pop_last(list_t *list)
{
	void *value = list->last->value;
	list_node_t *node = list->last;

	list->last = node->previous;
	free(node);

	--list->size;
	return value;
}


list_node_t *__new_list_node(void *value)
{
	list_node_t *node = malloc(sizeof(list_node_t));
	node->value    = value;
	node->next     = 0;
	node->previous = 0;
	return node;
}