Implement stack data structure and its operations using arrays.
Implement stack data structure and its operations using arrays.
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
class Stack {
private:
int top; // Index of the top element in the stack
int arr[MAX_SIZE]; // Array to store the stack elements
public:
Stack() {
top = -1; // Initialize top to -1 to indicate an empty stack
}
bool isEmpty() {
return (top == -1);
}
bool isFull() {
return (top == MAX_SIZE - 1);
}
void push(int value) {
if (isFull()) {
cout << "Stack Overflow: Cannot push element " << value << ". Stack is full." << endl;
return;
}
top++;
arr[top] = value;
cout << "Pushed element: " << value << endl;
}
void pop() {
if (isEmpty()) {
cout << "Stack Underflow: Cannot pop element. Stack is empty." << endl;
return;
}
int poppedElement = arr[top];
top--;
cout << "Popped element: " << poppedElement << endl;
}
int peek() {
if (isEmpty()) {
cout << "Stack is empty." << endl;
return -1;
}
return arr[top];
}
void display() {
if (isEmpty()) {
cout << "Stack is empty." << endl;
return;
}
cout << "Stack elements: ";
for (int i = 0; i <= top; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
};
int main() {
Stack stack;
stack.push(1);
stack.push(2);
stack.push(3);
stack.display();
cout << "Top element: " << stack.peek() << endl;
stack.pop();
stack.display();
stack.pop();
stack.pop();
stack.display();
return 0;
}
Comments
Post a Comment