Skip to content

Instantly share code, notes, and snippets.

@flyfire
Created October 5, 2013 15:34
Show Gist options
  • Save flyfire/6842362 to your computer and use it in GitHub Desktop.
Save flyfire/6842362 to your computer and use it in GitHub Desktop.
#ifndef STACK_H
#define STACK_H
#include <stdexcept>
template <typename T>
class Stack {
static const int MAX_SIZE = 100;
int top;
T stack[MAX_SIZE];
bool is_full() const { return top >= MAX_SIZE; }
public:
Stack(): top(-1) {}
bool is_empty() const { return top == -1; }
bool push(T &item);
T pop();
T get_top() const;
};
template <typename T>
bool Stack<T>::push(T &item) {
if (is_full()) {
return false;
}
stack[++top] = item;
return true;
}
template <typename T>
T Stack<T>::pop() {
if (is_empty()) {
throw std::underflow_error("stack is empty");
}
return stack[top--];
}
template <typename T>
T Stack<T>::get_top() const {
if (is_empty()) {
throw std::underflow_error("stack is empty");
}
return stack[top];
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment