This repository has been archived by the owner on Nov 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.c
97 lines (87 loc) · 1.61 KB
/
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
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
#include <stdlib.h>
#include "list.h"
list_t* list_new(void* data)
{
list_t* list = (list_t*) malloc(sizeof(list_t));
if (data)
{
list_node_t* initial_node = (list_node_t*) malloc(sizeof(list_node_t));
initial_node->data = data;
initial_node->next = NULL;
list->head = initial_node;
list->tail = initial_node;
list->length = 1;
}
else
{
list->head = NULL;
list->tail = NULL;
list->length = 0;
}
return list;
}
void list_del(list_t* list)
{
list_node_t* x = list->head;
while (x)
{
list_node_t* del = x;
x = x->next;
if (del->data)
free(del->data);
free(del);
}
free(list);
}
void list_enqueue(list_t* list, void* data)
{
list_node_t* new_node = (list_node_t*) malloc(sizeof(list_node_t));
new_node->data = data;
new_node->next = NULL;
if (list->length == 0)
{
list->head = new_node;
list->tail = new_node;
list->length = 1;
}
else
{
list->tail->next = new_node;
list->tail = new_node;
list->length++;
}
}
void* list_dequeue(list_t* list)
{
if (list->length == 0)
return NULL;
void* data = list->head->data;
if (list->length == 1)
{
free(list->head);
list->head = list->tail = NULL;
list->length = 0;
}
else
{
list_node_t* old_head = list->head;
list->head = list->head->next;
free(old_head);
list->length--;
}
return data;
}
void list_stack(list_t* list, void* data)
{
list_node_t* new_node = (list_node_t*) malloc(sizeof(list_node_t));
new_node->data = data;
new_node->next = list->head;
list->head = new_node;
list->length++;
if (list->length == 0)
list->tail = new_node;
}
void* list_unstack(list_t* list)
{
return list_dequeue(list);
}