view src/stack.c @ 9:abdba37f67a2

Red-black tree in progress. Linked list needs iterators redone, also in progress. Sleepy.
author Eris Caffee <discordia@eldalin.com>
date Fri, 28 Sep 2012 03:08:25 -0500
parents 5af32066927f
children
line source
1 #include <stdlib.h>
2 #include <errno.h>
4 #include "stack.h"
6 struct stack
7 {
8 void ** data;
9 size_t size;
10 size_t max;
11 };
13 ////////////////////////////////////////////////////////////////////////////////
14 struct stack * stack_new(size_t const max)
15 {
16 if (max < 1)
17 {
18 errno = EINVAL;
19 return NULL;
20 }
22 struct stack * s = malloc(sizeof(struct stack));
23 if (NULL == s)
24 return NULL;
26 s->size = 0;
27 s->max = max;
29 s->data = calloc(s->max, sizeof(void *));
30 if (NULL == s->data)
31 {
32 free(s);
33 return NULL;
34 }
36 return s;
37 }
39 ////////////////////////////////////////////////////////////////////////////////
40 void * stack_push(struct stack * s, void * elem)
41 {
42 if ((NULL == s) || (NULL == elem))
43 {
44 errno = EINVAL;
45 return NULL;
46 }
48 if (s->size == s->max)
49 {
50 errno = ENOMEM;
51 return NULL;
52 }
54 return s->data[(s->size)++] = elem;
55 }
57 ////////////////////////////////////////////////////////////////////////////////
58 void * stack_pop(struct stack * s)
59 {
60 if (NULL == s)
61 {
62 errno = EINVAL;
63 return NULL;
64 }
66 if (0 == s->size)
67 {
68 return NULL;
69 }
71 return s->data[--(s->size)];
72 }
74 ////////////////////////////////////////////////////////////////////////////////
75 size_t stack_size(struct stack * s)
76 {
77 if (NULL == s)
78 {
79 errno = EINVAL;
80 return -1;
81 }
83 return s->size;
84 }
86 ////////////////////////////////////////////////////////////////////////////////
87 void stack_delete(struct stack * s)
88 {
89 if (NULL != s) free(s->data);
90 free(s);
91 }