-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.h
More file actions
82 lines (68 loc) · 1.36 KB
/
stack.h
File metadata and controls
82 lines (68 loc) · 1.36 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
82
#ifndef _DS_STACK_H
#define _DS_STACK_H
/* Stack (Index) Data Structure (for array indexing)
* Namespace: stack
*
* Basic operation for implementing a array based stack.
*/
#include <stddef.h>
#include <stdbool.h>
/* Do not use top directly, use the methods */
struct StackIndex {
size_t size; /* size included as index */
size_t top; /* 0: underflow, valid between [1,size] */
};
typedef struct StackIndex StackIndex;
int stack_init(StackIndex *s, const size_t size)
{
if (s == NULL){
return -1;
}
s->size = size;
s->top = 0;
return 0;
}
bool stack_isempty(const StackIndex *s)
{
if (s == NULL){
return false;
}
return s->top == 0;
}
bool stack_isfull(const StackIndex *s)
{
if (s == NULL){
return false;
}
return s->top >= s->size;
}
/* return the index for setting the value in the support array.
* -1 in case of overflow
*/
long stack_push(StackIndex *s)
{
if (s == NULL){
return -1;
}
if (stack_isfull(s)){
return -1;
}
s->top++;
return (long)s->top-1;
}
/* return the index for getting the value in the support array.
* -1 in case of underflow
*/
long stack_pop(StackIndex *s)
{
if (s == NULL){
return -1;
}
if (stack_isempty(s)){
return -1;
}
long i = (long)s->top - 1;
s->top--;
return i;
}
#endif