- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstack.c
More file actions
Latest commit
70 lines (61 loc) · 1.43 KB
/
Copy pathstack.c
File metadata and controls
70 lines (61 loc) · 1.43 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
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"
voidinit(Stack*s, intelemSize, intmaxElements) {
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;
}
intisEmpty(Stack*s) {
/* top is 0 for an empty stack */
return (s->top==0);
}
intsize(Stack*s) {
returns->top;
}
voidpush(Stack*s, void*elem) {
if(s->top==s->maxElements) {
fprintf(stderr, "Element can not be pushed: Stack is full.\n");
exit(1);
}
intstart=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;
returnelem;
}
void*top(Stack*s) {
if(isEmpty(s)) {
fprintf(stderr, "Can not pop from an empty stack.\n");
exit(1);
}
intstart= (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;
}
voiddestroy(Stack*s) {
free(s->storage);
s->top=0;
}