-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStackImplementation.c
68 lines (56 loc) · 1.33 KB
/
StackImplementation.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
//QUESTION: Implement a stack using arrays.
//CODE:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
typedef struct Stack {
int arr[MAX];
int top;
} Stack;
// Function to initialize the stack
void initialize(Stack *stack) {
stack->top = -1;
}
// Function to check if the stack is empty
int isEmpty(Stack *stack) {
return stack->top == -1;
}
// Function to check if the stack is full
int isFull(Stack *stack) {
return stack->top == MAX - 1;
}
// Function to push an element onto the stack
void push(Stack *stack, int value) {
if (isFull(stack)) {
printf("Stack Overflow\n");
return;
}
stack->arr[++(stack->top)] = value;
printf("%d pushed to stack\n", value);
}
// Function to pop an element from the stack
int pop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
return -1;
}
return stack->arr[(stack->top)--];
}
// Function to peek the top element of the stack
int peek(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
return stack->arr[stack->top];
}
int main() {
Stack stack;
initialize(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
printf("%d popped from stack\n", pop(&stack));
printf("Top element is %d\n", peek(&stack));
return 0;
}