-
Notifications
You must be signed in to change notification settings - Fork 3
/
stack.c
70 lines (61 loc) · 1.43 KB
/
stack.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
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
void init(Stack *s, int elemSize, int maxElements) {
byte *storage;
/* Try to allocate memory */
storage = (byte *)malloc(elemSize * maxElements);
if(storage == NULL) {
fprintf(stderr, "Insufficient memory to initialize stack.\n");
exit(1);
}
/* Initialize an empty stack */
s->top = 0;
s->maxElements = maxElements;
s->elemSize = elemSize;
s->storage = storage;
}
int isEmpty(Stack *s) {
/* top is 0 for an empty stack */
return (s->top == 0);
}
int size(Stack *s) {
return s->top;
}
void push(Stack *s, void *elem) {
if(s->top == s->maxElements) {
fprintf(stderr, "Element can not be pushed: Stack is full.\n");
exit(1);
}
int start = s->top * s->elemSize, i;
for(i = 0; i < s->elemSize; i++) {
*(s->storage + start + i) = *((byte *)(elem + i));
}
s->top = s->top + 1;
}
void* pop(Stack *s) {
if(isEmpty(s)) {
fprintf(stderr, "Can not pop from an empty stack.\n");
exit(1);
}
void *elem = top(s);
s->top = s->top - 1;
return elem;
}
void* top(Stack *s) {
if(isEmpty(s)) {
fprintf(stderr, "Can not pop from an empty stack.\n");
exit(1);
}
int start = (s->top - 1) * s->elemSize, i;
byte *elem;
elem = (byte *)malloc(s->elemSize);
for(i = 0; i < s->elemSize; i++) {
*(elem + i) = *(s->storage + start + i);
}
return (void *)elem;
}
void destroy(Stack *s) {
free(s->storage);
s->top = 0;
}