-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_array.c
More file actions
executable file
·118 lines (106 loc) · 1.81 KB
/
stack_array.c
File metadata and controls
executable file
·118 lines (106 loc) · 1.81 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
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
110
111
112
113
114
115
116
117
// Last In First Out (LIFO)
#include <stdio.h>
#include "stack.h"
#define MAX 5
int stack_arr[MAX];
int top = -1;
int main(void)
{
printf("Before pop()\n");
push(10);
push(20);
push(30);
push(40);
push(50);
print_stack();
printf("\nAfter pop()\n");
int p = pop();
printf("You deleted %d\n", p);
p = pop();
printf("You deleted %d\n", p);
p = pop();
printf("You deleted %d\n", p);
print_stack();
return 0;
}
/**
* is_full - Checks if the stack is full.
*
* Returns: 1 if the stack is full, 0 otherwise.
*/
int is_full()
{
if (top == MAX - 1)
return 1;
else
return 0;
}
/**
* is_empty - Checks if the stack is empty.
*
* Returns: 1 if the stack is empty, 0 otherwise.
*/
int is_empty()
{
if (top == -1)
return 1;
else
return 0;
}
/**
* push - Pushes an element onto the stack.
* @data: The data to be pushed onto the stack.
*/
void push(int data)
{
if (is_full())
{
printf("Stack overflow\n");
return;
}
top++;
stack_arr[top] = data;
}
/**
* pop - Pops an element from the stack.
*
* Returns: The value of the popped element.
*/
int pop()
{
if (is_empty())
{
printf("Stack is underflow\n");
exit(1);
}
int value = stack_arr[top];
top--;
return value;
}
/**
* peek - Returns the value of the top element without removing it.
*
* Returns: The value of the top element.
*/
int peek()
{
if (is_empty())
{
printf("Stack underflow\n");
exit(1);
}
return stack_arr[top];
}
/**
* print_stack - Prints the elements in the stack.
*/
void print_stack()
{
if (is_empty())
{
printf("Stack is underflow\n");
return;
}
for (int i = top; i >= 0; i--)
printf("%d\n", stack_arr[i]);
}