-
Notifications
You must be signed in to change notification settings - Fork 2
/
stack_using_array_simple.c
109 lines (85 loc) · 1.64 KB
/
stack_using_array_simple.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/****************************************************************************
File name: stack_using_array_simple.c
Author: babajr
*****************************************************************************/
/*
Here instead of using structure to have arr, size and top, we will use
global array, size and top as a single variables.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#define MAX_SIZE 100
// We will use global array and top
int arr[MAX_SIZE];
int top = -1;
/*API to push the elements on the stack.*/
void push(int val)
{
// check for stack overflow
if(top == MAX_SIZE - 1)
{
printf("STACK OVERFLOW\n");
return;
}
arr[++top] = val;
}
/*API to pop the elements from the stack.*/
void pop()
{
// check for empty stack
if(top == -1)
{
printf("ERROR: No element to POP\n");
return;
}
top--;
}
/*
API to return the top element of the stack.
*/
int stack_top()
{
if(top == -1)
{
printf("ERROR: stack is empty\n");
return -1;
}
return arr[top];
}
bool is_empty()
{
if(top == -1)
return 1;
else
return 0;
}
bool is_full()
{
if(top == MAX_SIZE - 1)
return 1;
else
return 0;
}
/*API to print the elements on the stack.*/
void print_stack()
{
printf("Stack : ");
for(int i = 0; i <= top; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main(void)
{
push(1);
print_stack();
push(2);
print_stack();
push(3);
print_stack();
pop();
print_stack();
printf("TOP of stack: %d\n", stack_top());
return 0;
}