-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
82 lines (61 loc) · 1.61 KB
/
stack.c
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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Stack{
int maxsize;
int top;
int* element;
}stack_for_int;
bool ISisFull();
bool ISisEmpty();
stack_for_int* ISCreate();
void ISpush();
int ISpop();
stack_for_int* ISCreate(int stackSize){
stack_for_int* newStack = (stack_for_int*)malloc(sizeof(stack_for_int));
newStack->top = -1;
newStack->maxsize = stackSize;
newStack->element = (int*)malloc(sizeof(int) * stackSize);
return newStack;
}
bool ISisEmpty(stack_for_int* Stack){
return Stack->top == -1;
}
bool ISisFull(stack_for_int* Stack){
return Stack->maxsize - 1 == Stack->top;
}
// function won't be able to modify globally if it is passed by value. In this case Stack->element is value,
// but Stack->element points to another memory location where stores an array is fine(?) (I hope i understand it right)
void ISpush(stack_for_int* Stack, int value){
if (ISisFull(Stack)){
printf("Stack Overflow...\n");
return;
}
Stack->element[++(Stack->top)] = value;
}
int ISsize(stack_for_int* Stack){
return Stack->top+1;
}
int ISpeek(stack_for_int* Stack){
return Stack->element[Stack->top];
}
int ISpop(stack_for_int* Stack){
if (ISisEmpty(Stack)){
printf("Stack Underflow... \n");
return 0;
}
return Stack->element[Stack->top--];
}
int main(){
stack_for_int* a;
a = ISCreate(10);
ISpush(a, 10);
ISpush(a,6);
ISpush(a,33);
printf("%d\n",ISsize(a));
int l = ISpop(a);
printf("%d\n",l);
printf("%d\n",ISsize(a));
printf("%d\n",ISpeek(a));
return 0;
}