forked from Raj217/Stack-in-C
-
Notifications
You must be signed in to change notification settings - Fork 2
/
stack.h
90 lines (81 loc) · 3.79 KB
/
stack.h
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
83
84
85
86
87
88
89
90
#define stack_min_capacity 3
#define stack_struct(T) \
typedef struct T##_stack \
{ \
T *buf; \
size_t capacity; \
size_t size; \
size_t top; \
} T##_stack;
#define stack_init(T) \
void T##_stack_init(T##_stack *vec) \
{ \
vec->capacity = stack_min_capacity; \
vec->buf = malloc(sizeof(T) * vec->capacity); \
vec->size = 0; \
vec->top = -1; \
}
#define stack_get(T) \
T T##_stack_get(T##_stack *vec, size_t idx) \
{ \
if (idx < 0 || idx >= vec->size) \
{ \
fprintf(stderr, "Index not valid! Exiting...\n"); \
exit(-1); \
} \
return *(vec->buf + idx); \
}
#define stack_set(T) \
void T##_stack_set(T##_stack *vec, size_t idx, T data) \
{ \
vec->buf[idx] = data; \
}
#define stack_push(T) \
void T##_stack_push(T##_stack *vec, T data) \
{ \
if (vec->size == vec->capacity) \
{ \
vec->capacity *= 2; \
vec->size++; \
vec->buf = realloc(vec->buf, sizeof(T) * vec->capacity); \
} \
T##_stack_set(vec, vec->size++, data); \
vec->top++; \
}
#define stack_top(T) \
T T##_stack_top(T##_stack *vec) \
{ \
return *(vec->buf + vec->top); \
}
#define stack_size(T) \
size_t T##_stack_size(T##_stack *vec) \
{ \
return vec->size; \
}
#define stack_pop(T) \
T T##_stack_pop(T##_stack *vec) \
{ \
if (vec->size == 0) \
{ \
fprintf(stderr, "Stack is Empty! Exiting...\n"); \
exit(-1); \
} \
T x = T##_stack_get(vec, vec->top); \
vec->top--; \
return x; \
}
#define stack(T) \
stack_struct(T); \
stack_init(T) stack_get(T) stack_set(T) stack_push(T) stack_pop(T) \
stack_top(T) stack_size(T)
/*
stack(T)=>Determines type of stack i.e T
stac_init(&V)=>creates the stack V of type T
stack_get(&V,int index)=>gets the value from the index i.e fond
function
stack_top()
stack_size()
stack_set(&V,int index,T data)=> changes the value at index
stack_push(&V,val)
stack_pop(&V)
*/