Stack
Stack
● Every stack has a variable top associated with it. top is used to store
the address of the
topmost element of the stack. It is this position from where the
element will be added or
deleted. There is another variable MAX, which is used to store the
maximum number of
elements that the stack can store.
● If top = NULL, then it indicates that the stack is empty
● and if top = MAX–1, then the stack is full.
#define MAX 5
int stack[MAX];
int top = -1;
void push(int x) {
if (top == MAX - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = x;
}
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}
int peek() {
if (top == -1) {
printf("Stack is empty\n");
return -1;
}
return stack[top];
}
void printStack() {
for (int i = 0; i <= top; i++) {
printf("%d ", stack[i]);
}
printf("\n");
}
int main() {
push(1);
push(2);
push(3);
printStack(); // prints: 1 2 3
printf("Top element: %d\n", peek()); // prints: Top element: 3
printf("Popped: %d\n", pop()); // prints: Popped: 3
printStack(); // prints: 1 2
printf("Top element: %d\n", peek()); // prints: Top element: 2
return 0;
}