aboutsummaryrefslogtreecommitdiff
path: root/src/lib/ll.c
blob: 4918194804f3c30258dd278832256bc00ec46095 (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
#include <lib/ll.h>
#include <lib/mem.h>

struct LL* new_ll(void* val)
{
	struct LL* ll = (struct LL*)malloc(sizeof(struct LL));
	ll->prev = ll;
	ll->next = ll;
	ll->data = val;
	return ll;
}

void push_ll(struct LL* l, void* val)
{
	struct LL* ll = (struct LL*)malloc(sizeof(struct LL));
	l->prev->next = ll;
	ll->prev = l->prev;
	ll->next = l;
	l->prev = ll;
	ll->data = val;
}

void pop_ll(struct LL* l)
{
	if ((l->prev == l->next) && (l->prev == l))
		l->data = 0;
	else {
		l->prev->next = l->next;
		l->next->prev = l->prev;
		free(l);
	}
}

void remove_ll(struct LL* l, unsigned long idx)
{
	struct LL* t = l;
	for(unsigned long i = 0; i < idx; i++) {
		t = t->next;
	}
	t->prev->next = t->next;
	t->next->prev = t->prev;
	free(t);
}

unsigned long length_ll(struct LL* l)
{
	struct LL* t = l;
	unsigned long len = 0;
	while (1) {
		if (t->next == l) {
			return len;
		}
		len++;
		t = t->next;
	}
	return len;
}