forked from fgrandoinf/centrality-measures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.cpp
52 lines (39 loc) · 1.2 KB
/
stack.cpp
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
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
void StackInit(stack *stackP, int maxSize) {
stackElement *newContents;
/* Allocate a new array to hold the contents. */
newContents = (stackElement *) malloc(sizeof(stackElement) * maxSize);
if (newContents == NULL) {
fprintf(stderr, "Insufficient memory to initialize stack.\n");
exit(1); /* Exit, returning error code. */
}
stackP->contents = newContents;
stackP->maxSize = maxSize;
stackP->top = -1; /* I.e., empty */
}
void StackDestroy(stack *stackP) {
free(stackP->contents);
}
void StackPush(stack *stackP, stackElement element) {
if (StackIsFull(stackP)) {
fprintf(stderr, "Can't push element on stack: stack is full.\n");
exit(1); /* Exit, returning error code. */
}
/* Put information in array; update top. */
stackP->contents[++stackP->top] = element;
}
stackElement StackPop(stack *stackP) {
if (StackIsEmpty(stackP)) {
fprintf(stderr, "Can't pop element from stack: stack is empty.\n");
exit(1); /* Exit, returning error code. */
}
return stackP->contents[stackP->top--];
}
int StackIsEmpty(stack *stackP) {
return stackP->top < 0;
}
int StackIsFull(stack *stackP) {
return stackP->top >= stackP->maxSize - 1;
}