-
Notifications
You must be signed in to change notification settings - Fork 0
/
2. stacks extra KNowledge of push pop empty ful top peek.c
79 lines (66 loc) · 1.85 KB
/
2. stacks extra KNowledge of push pop empty ful top peek.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
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5
int stack[MAX_SIZE];
int topN = -1;
// Function to push an element onto the stack
void push(int x) {
if (topN == MAX_SIZE - 1) {
// Stack overflow
printf("Stack Overflow! Warning\n");
} else {
topN++;
stack[topN] = x;
printf("%d pushed onto the stack\n", x);
}
}
// Function to pop an element from the stack
int pop() {
if (topN == -1) {
// Stack underflow
printf("Stack Underflow! Warning\n");
return -1; // Return an invalid value (you may choose a different approach)
} else {
int poppedElement = stack[topN];
topN--;
return poppedElement;
}
}
// Function to get the top elemenf the stack without removing it
int top() {
if (topN == -1) {
// Stack is empty
printf("Stack is empty\n");
return -1; // Return an invalid value (you may choose a different approach)
}
else {
return stack[topN];
}
}
// Function to check if the stack is empty
int isEmpty() {
if(topN==-1){
return 1;}
else{
return 0;
}
}
int isFull(){
return topN== MAX_SIZE-1;}
int main() {
push(10);
push(20);
push(30);
push(50);
push(60);
printf("Top element: %d\n", top()); // Should print: 60
// Print the top element without removing it
// Pop some elements
printf("%d popped out of the stack\n", pop()); // Popped: 60
printf("%d popped out of the stack\n", pop()); // Popped: 50
// Print the new top element without removing it
printf("New top element: %d\n", top()); // Should print: 30
printf("Is the stack empty? %s\n", isEmpty() ? "Yes" : "No");
printf("Is the stack full? %s\n", isFull() ? "Yes" : "No");
return 0;
}