-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
82 lines (75 loc) · 1.19 KB
/
stack.c
File metadata and controls
82 lines (75 loc) · 1.19 KB
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
# include <stdlib.h>
# include <stdio.h>
# include "stack.h"
stack *newStack(uint32_t size)
{
stack *s = (stack *) malloc(sizeof(stack));
if (s)
{
s->size = size;
s->top = 0;
s->entries = (stackItem *) calloc(s->size, sizeof(stackItem));
if (s->entries)
{
return s;
}
}
return (stack *) 0;
}
void delStack(stack *s)
{
free(s->entries);
s->entries = NIL;
free(s);
s = NIL;
}
/* pop:
*
* Removes the top item.
*
* Sets stackItem *i to the popped item.
*/
bool pop(stack *s, stackItem *i)
{
if (!emptyStack(s))
{
s->top -= 1;
*i = s->entries[s->top];
return true;
}
return false;
}
/* push:
*
* Adds an item to the top.
* Reallocs an additional 'size' of the stack if it is full.
*/
bool push(stack *s, stackItem i)
{
if (fullStack(s))
{
stackItem *tmp = (stackItem *) realloc(s->entries, sizeof(stackItem) * s->size * 2);
if (tmp)
{
s->size *= 2; // double size to reduce number of realloc calls
s->entries = tmp;
}
else
{
free(tmp);
tmp = NIL;
return false;
}
}
s->entries[s->top] = i;
s->top += 1;
return true;
}
bool emptyStack(const stack *s)
{
return s->top == 0;
}
bool fullStack(const stack *s)
{
return s->top == s->size;
}