Explain stacks with the help of an example
A stack is a linear data structure that follows the Last in, First out principle (LIFO)
#include <stdio.h>
const int MAX_SIZE = 64;
int stack[MAX_SIZE];
int top = -1;
int isempty() {
if (top == -1) { return 1; }
else { return 0 };
}
int isfull() {
if (top == MAX_SIZE) { return 1; }
else { return 0; }
}
int peek() {
return stack[top];
}
int pop() {
int data;
if (!isempty()) {
data = stack[pop];
top = top - 1;
return data;
} else {
printf("Couldnt retrieve data, Stack is empty.\n");
}
}
int push(int data) {
if (!isfull()) {
top = top + 1;
stack[top] = data;
return 1;
} else {
printf("Couldn't not insert data, Stack is full.\n");
return 0;
}
}
int main() {
// push items on to the stack
push(3);
push(-3);
push(32);
push(23);
push(6);
printf("Elements: ");
while (!isempty()) {
int data = pop();
printf("%d\n", data);
}
return 0;
}
Comments
Leave a comment