-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid stack.cpp
More file actions
80 lines (63 loc) · 1.56 KB
/
Copy pathvalid stack.cpp
File metadata and controls
80 lines (63 loc) · 1.56 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
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
struct Stack {
int items[MAX_SIZE];
int top;
};
void initialize(struct Stack *s) {
s->top = -1;
}
int isFull(struct Stack *s) {
return s->top == MAX_SIZE - 1;
}
int isEmpty(struct Stack *s) {
return s->top == -1;
}
void push(struct Stack *s, int value) {
if (isFull(s)) {
printf("Stack Overflow: Cannot push element %d, stack is full.\n", value);
return;
}
s->items[++s->top] = value;
printf("%d pushed to stack\n", value);
}
int pop(struct Stack *s) {
if (isEmpty(s)) {
printf("Stack Underflow: Cannot pop element, stack is empty.\n");
return -1;
}
return s->items[s->top--];
}
int peek(struct Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return -1;
}
return s->items[s->top];
}
void printStack(struct Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return;
}
printf("Stack elements: ");
for (int i = 0; i <= s->top; ++i) {
printf("%d ", s->items[i]);
}
printf("\n");
}
int main() {
struct Stack stack;
initialize(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
push(&stack, 40);
printStack(&stack);
printf("Top element: %d\n", peek(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack));
printStack(&stack);
return 0;
}