Skip to content

Instantly share code, notes, and snippets.

@Amadeeus
Last active May 26, 2019 23:24
Show Gist options
  • Save Amadeeus/b9b3f8ace81d0f99b26635795b6b72fd to your computer and use it in GitHub Desktop.
Save Amadeeus/b9b3f8ace81d0f99b26635795b6b72fd to your computer and use it in GitHub Desktop.
C++ Stack Implementation (array-based)
#include <array>
#include <exception>
#include <iostream>
template <typename T>
class Stack {
public:
T *stack_array_;
int top_;
int capacity_;
public:
Stack(const int& size);
~Stack();
bool isEmpty() {
return top_ == -1;
}
bool isFull() {
return top_ == capacity_ - 1;
}
void push(T value);
T pop();
T peek();
void display();
int size();
};
template <typename T>
Stack<T>::Stack(const int& size) {
stack_array_ = new T[size];
top_ = -1;
capacity_ = size;
}
template <typename T>
Stack<T>::~Stack() {
delete[] stack_array_;
std::cout << "Stack deleted." << std::endl;
}
template <typename T>
void Stack<T>::push(T value) {
if (!isFull()) {
stack_array_[++top_] = value;
} else {
std::cout << "Stack is full." << std::endl;
}
}
template <typename T>
T Stack<T>::pop() {
if (!isEmpty()) {
T value = stack_array_[top_];
top_--;
return value;
} else {
throw std::underflow_error("Stack is empty.");
}
}
template <typename T>
T Stack<T>::peek() {
if (!isEmpty()) {
std::cout << "Current top element: "
<< stack_array_[top_] << std::endl;
return stack_array_[top_];
} else {
throw std::underflow_error("Stack is empty.");
}
}
template <typename T>
void Stack<T>::display() {
if (!isEmpty()) {
for (int i = 0; i <= top_; i++) {
std::cout << stack_array_[i] << ' ';
}
std::cout << std::endl;
} else {
std::cout << "Stack is empty." << std::endl;
}
}
template <typename T>
int Stack<T>::size() {
if (!isEmpty()) {
std::cout << "Current number of stack elements: "
<< top_ + 1 << std::endl;
return top_ + 1;
} else {
std::cout << "Stack is empty." << std::endl;
return 0;
}
}
int main(){
Stack<int> *stack = new Stack<int>(10);
stack->push(5);
stack->push(2);
stack->push(5);
stack->push(1);
stack->push(3);
stack->push(3);
stack->push(2);
stack->push(1);
stack->push(1);
stack->push(9);
stack->display(); // 5 2 5 1 3 3 2 1 1 9
stack->pop();
stack->display(); // 5 2 5 1 3 3 2 1 1
stack->peek(); // Current top element: 1
stack->size(); // Current number of stack elements: 9
stack->pop();
stack->pop();
stack->pop();
stack->display(); // 5 2 5 1 3 3
while (!stack->isEmpty()) {
stack->pop();
}
stack->display(); // Stack is empty.
delete stack;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment