-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintstack.c
More file actions
79 lines (66 loc) · 1.63 KB
/
intstack.c
File metadata and controls
79 lines (66 loc) · 1.63 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
/*
* intstack
*
* Created on: Nov 21, 2019
* Author: Chris Burke
* Based on:
* https://github.com/igniting/generic-stack/blob/master/stack.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "intstack.h"
void intstack_init(IntStack *s, int maxElements) {
unsigned *storage;
/* Try to allocate memory */
storage = (unsigned *)malloc(sizeof(unsigned) * 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->storage = storage;
}
int intstack_isEmpty(IntStack *s) {
/* top is 0 for an empty stack */
return (s->top == 0);
}
int intstack_size(IntStack *s) {
return s->top;
}
void intstack_push(IntStack *s, unsigned elem) {
if (s->top == s->maxElements) {
fprintf(stderr, "Element can not be pushed: Stack is full.\n");
exit(1);
}
(s->storage)[s->top++] = elem;
}
unsigned intstack_pop(IntStack *s) {
if (intstack_isEmpty(s)) {
fprintf(stderr, "Can not pop from an empty stack.\n");
exit(1);
}
return (s->storage)[--s->top];
}
unsigned intstack_top(IntStack *s) {
if (intstack_isEmpty(s)) {
fprintf(stderr, "Can not check top of an empty stack.\n");
exit(1);
}
return (s->storage)[s->top-1];
}
unsigned intstack_probe(IntStack *s, int fromTop) {
if ((fromTop<0) || (fromTop>=s->top)) {
fprintf(stderr, "Stack probe index invalid.\n");
exit(1);
}
return (s->storage)[s->top-fromTop-1];
}
void intstack_destroy(IntStack *s) {
if (s && s->storage) {
free(s->storage);
s->top = 0;
}
}