Created
November 24, 2017 14:42
-
-
Save ArtyomLazyan/cecc5cfe9eb48c886341e6825ff680f5 to your computer and use it in GitHub Desktop.
Stack with templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <exception> | |
template <typename T> | |
class Stack | |
{ | |
public: | |
Stack() : m_top(NULL), m_size(0) {} | |
void push(const T); | |
void pop(); | |
T& top(); | |
int size(); | |
bool empty(); | |
private: | |
class Node | |
{ | |
public: | |
Node (T el) : data(el) {} | |
Node (T el, Node *node) : data(el), next(node) {} | |
T data; | |
Node *next; | |
}; | |
Node* m_top; | |
int m_size; | |
}; | |
template <typename T> | |
void Stack<T>::push(const T el) | |
{ | |
try | |
{ | |
if (m_top != NULL) | |
{ | |
Node *temp = new Node(el, m_top); | |
m_top = temp; | |
} | |
else | |
{ | |
m_top = new Node(el); | |
} | |
m_size++; | |
} | |
catch(std::bad_alloc) | |
{ | |
std::cout << "Bad alloc" << std::endl; | |
} | |
} | |
template <typename T> | |
void Stack<T>::pop() | |
{ | |
try | |
{ | |
if (m_top == NULL) | |
{ | |
throw std::out_of_range("Error Out of range."); | |
} | |
else | |
{ | |
Node *temp = m_top; | |
m_top = m_top->next; | |
delete temp; | |
} | |
m_size--; | |
} | |
catch(std::exception &e) | |
{ | |
std::cout << e.what() << std::endl; | |
} | |
} | |
template <typename T> | |
T& Stack<T>::top() | |
{ | |
try | |
{ | |
if (m_top == NULL) | |
throw std::out_of_range("Error out of range."); | |
} | |
catch(std::exception &e) | |
{ | |
std::cout << e.what() << std::endl; | |
} | |
return m_top->data; | |
} | |
template <typename T> | |
int Stack<T>::size() | |
{ | |
return m_size; | |
} | |
template <typename T> | |
bool Stack<T>::empty() | |
{ | |
return m_size == 0 ? true : false; | |
} | |
int main() | |
{ | |
Stack<int> stack; | |
stack.push(11); | |
stack.push(12); | |
stack.push(1); | |
stack.push(8); | |
while (!stack.empty()) | |
{ | |
std::cout << stack.top() << " - " << stack.size() << std::endl; | |
stack.pop(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment