aboutsummaryrefslogtreecommitdiff
path: root/list-tail-node.c
diff options
context:
space:
mode:
Diffstat (limited to 'list-tail-node.c')
-rw-r--r--list-tail-node.c129
1 files changed, 129 insertions, 0 deletions
diff --git a/list-tail-node.c b/list-tail-node.c
new file mode 100644
index 0000000..d187241
--- /dev/null
+++ b/list-tail-node.c
@@ -0,0 +1,129 @@
1/* Standard C */
2#include <stdbool.h>
3#include <stdio.h>
4#include <stdlib.h>
5
6/* Project */
7#include "util.h"
8
9typedef int T;
10
11struct list_node {
12 struct list_node *next;
13 T data;
14};
15
16struct list {
17 struct list_node *head, *tail;
18};
19
20void
21list_init(struct list *list)
22{
23 list->head = NULL;
24}
25
26static struct list_node *
27create_node(struct list_node *next, T data)
28{
29 struct list_node *node = malloc(sizeof *node);
30
31 if ( node != NULL ) {
32 node->next = next;
33 node->data = data;
34 }
35 return node;
36}
37
38void
39list_push_back(struct list *list, T data)
40{
41 struct list_node *node = create_node(NULL, data);
42
43 if ( node != NULL ) {
44 if ( list->head == NULL ) {
45 list->head = node;
46 }
47 else {
48 list->tail->next = node;
49 }
50 list->tail = node;
51 }
52 else {
53 ERROR("out of memory");
54 }
55}
56
57void
58list_push_front(struct list *list, T data)
59{
60 struct list_node *node = create_node(list->head, data);
61
62 if ( node != NULL ) {
63 if ( list->head == NULL ) { // Einfügen in eine leere Liste?
64 list->tail = node;
65 }
66 list->head = node;
67 }
68 else {
69 ERROR("out of memory");
70 }
71}
72
73bool
74list_pop_front(struct list *list, T *data)
75{
76 if ( list->head != NULL ) {
77 struct list_node *next = list->head->next;
78 *data = list->head->data;
79 free(list->head);
80 list->head = next;
81
82 return true;
83 }
84 else
85 return false;
86}
87
88bool
89list_empty(struct list *list)
90{
91 return list->head == NULL;
92}
93
94void
95list_free(struct list *list)
96{
97 struct list_node *item, *next;
98
99 for ( item = list->head; item; item = next ) {
100 next = item->next;
101 free(item);
102 }
103}
104
105int
106main()
107{
108 struct list list[1];
109
110 list_init(list);
111
112 for ( int i = 0; i != 10; ++i )
113 list_push_front(list, -i);
114
115 for ( int i = 0; i != 10; ++i )
116 list_push_back(list, i);
117
118 while ( !list_empty(list) ) {
119 int i;
120 if ( list_pop_front(list, &i) )
121 printf("%d\n", i);
122 else
123 ERROR("this shouldn't happen!");
124 }
125
126 list_free(list);
127
128 return EXIT_SUCCESS;
129}