Stack Lab
Stack Lab
In data structures, a stack is a linear data structure that follows the Last In, First Out (LIFO)
principle. It means that the last element added to the stack is the first one to be removed. The
operations on a stack typically include:
This program defines a `Stack` class that uses an array to implement stack operations. It
includes methods like `push`, `pop`, `peek`, `isEmpty`, and `isFull` to manage elements in the
stack.
Example 1: A C++ program to implement a stack using an array:
#include <iostream>
using namespace std;
#define MAX_SIZE 100 // Maximum size of the stack
class Stack {
private:
int top; // Top of the stack
int arr[MAX_SIZE]; // Array to store elements
public:
Stack() {
top = -1; // Initialize top to -1 (empty stack)
}
bool isEmpty() {
return (top == -1); // Check if stack is empty
}
bool isFull() {
return (top == MAX_SIZE - 1); // Check if stack is full
}
void push(int value) {
if (isFull()) {
cout << "Stack Overflow: Cannot push element. Stack is full." << endl;
return;
}
arr[++top] = value; // Increment top and add element
cout << value << " pushed to stack." << endl;
}
void pop() {
if (isEmpty()) {
cout << "Stack Underflow: Cannot pop element. Stack is empty." << endl;
return;
}
cout << arr[top--] << " popped from stack." << endl; // Remove top element
}
int peek() {
if (isEmpty()) {
cout << "Stack is empty." << endl;
return -1; // Return -1 for an empty stack
}
return arr[top]; // Return top element
}
};
int main() {
Stack myStack;
myStack.push(5);
myStack.push(10);
myStack.push(15);
cout << "Top element: " << myStack.peek() << endl;
myStack.pop();
myStack.pop();
cout << "Top element after pops: " << myStack.peek() << endl;
return 0;
}
Compile and run this code in a C++ compiler to see how a stack works using an array-based
implementation.