Let's Implement the ADT (The "How")
Implementation 1: ArrayStack (Using an Array)
class ArrayStack : public Stack {
private:
int* array;
int capacity;
int topIndex; // Index of the top element
public:
ArrayStack(int size) {
capacity = size;
array = new int[capacity];
topIndex = -1; // Signifies an empty stack
}
~ArrayStack() {
delete[] array; // Clean up dynamic memory
}
void push(int value) override {
if (topIndex >= capacity - 1) {
cout << "Stack Overflow!" << endl;
return;
}
array[++topIndex] = value;
}
, int pop() override {
if (isEmpty()) {
cout << "Stack Underflow!" << endl;
return -1; // Error value
}
return array[topIndex--];
}
int peek() const override {
if (isEmpty()) {
cout << "Stack is Empty!" << endl;
return -1;
}
return array[topIndex];
}
bool isEmpty() const override {
return topIndex == -1;
}
};
Implementation 1: ArrayStack (Using an Array)
class ArrayStack : public Stack {
private:
int* array;
int capacity;
int topIndex; // Index of the top element
public:
ArrayStack(int size) {
capacity = size;
array = new int[capacity];
topIndex = -1; // Signifies an empty stack
}
~ArrayStack() {
delete[] array; // Clean up dynamic memory
}
void push(int value) override {
if (topIndex >= capacity - 1) {
cout << "Stack Overflow!" << endl;
return;
}
array[++topIndex] = value;
}
, int pop() override {
if (isEmpty()) {
cout << "Stack Underflow!" << endl;
return -1; // Error value
}
return array[topIndex--];
}
int peek() const override {
if (isEmpty()) {
cout << "Stack is Empty!" << endl;
return -1;
}
return array[topIndex];
}
bool isEmpty() const override {
return topIndex == -1;
}
};