-
Notifications
You must be signed in to change notification settings - Fork 9
/
linked_list.c
58 lines (52 loc) · 1.06 KB
/
linked_list.c
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
#include "libc.h"
#include "linked_list.h"
linked_list *new_linked_list()
{
linked_list *l = (linked_list *)malloc(sizeof(linked_list));
l->first = NULL;
l->last = NULL;
l->count = 0;
return l;
}
void add_to_list(linked_list *l, void *value)
{
list_node *node = (list_node *)malloc(sizeof(list_node));
node->value = value;
node->next = NULL;
node->prev = l->last;
if (l->first == NULL)
{
l->first = node;
l->last = node;
}
else
{
l->last->next = node;
l->last = node;
}
l->count++;
}
void pop_list(linked_list *l)
{
if (l->last)
{
list_node *new_last = l->last->prev;
if (new_last)
new_last->next = NULL;
l->last = new_last;
l->count--;
// When we pop the last element also set the first to null
if (l->count == 0)
l->first = NULL;
}
}
void free_list(linked_list *l)
{
list_node *ptr = l->first;
while (ptr)
{
list_node *tmp = ptr;
ptr = ptr->next;
free(tmp);
}
}