Stack C++
Stack Header (Stack.h)
#ifndef STACK_h
#define STACK_h
// Define the default capacity of the stack
#define SIZE 10
// A class to represent a stack
class stack
{
int *arr;
int top;
int capacity;
public:
stack(int size = SIZE); // Constructor
~stack(); // Destructor
void push(int); // Push onto the Stack
int pop(); // Pop value from Stack
int peek(); // See the top value on the Stack
int size(); // Size of the Stack
bool isEmpty(); // Check Stack is empty
bool isFull(); // Check is Stack is full
};
#endif
Stack Functions (Stack.cpp)
#include<iostream>
using std::cout;
using std::endl;
#include "stack.h"
// Constructor to initialize the stack
stack::stack(int size)
{
arr = new int[size];
capacity = size;
top = -1; // index
}
// Destructor to free memory allocated to the stack
stack::~stack() {
delete[] arr;
}
void stack::push(int x)
{
if (isFull())
{
cout << "Overflow Program Terminated" << endl;
}
cout << "Inserting " << x << endl;
// Add value to the Stack
arr[++top] = x;
}
// Utility function to pop a top element from the stack
int stack::pop()
{
if (isEmpty())
{
cout << "Underflow Program Terminated " << endl;
}
cout << "Removing " << peek() << endl;
// decrease stack size by 1 and (optionally) return the popped element
return arr[top--];
}
// Utility function to return the top element of the stack
int stack::peek()
{
if (!isEmpty()) {
return arr[top];
}
else {
cout << "Stack is Empty " << endl;
}
}
// Utility function to return the size of the stack
int stack::size() {
return top + 1;
}
// Utility function to check if the stack is empty or not
bool stack::isEmpty() {
return size() == 0;
}
// Utility function to check if the stack is full or not
bool stack::isFull() {
return size() == capacity;
}
Main File (main.cpp)
#include<iostream>
using std::cout;
using std::endl;
#include "stack.h"
int main()
{
stack pt(3);
pt.push(1);
pt.push(2);
pt.pop();
pt.pop();
pt.push(3);
cout << "The top element is " << pt.peek() << endl;
cout << "The stack size is " << pt.size() << endl;
pt.pop();
if (pt.isEmpty()) {
cout << "The stack is empty\n";
}
else {
cout << "The stack is not empty\n";
}
}
Output:
Inserting 1
Inserting 2
Removing 2
Removing 1
Inserting 3
The top element is 3
The stack size is 1