Advertisement
jtentor

DemoStack2 - Cpp - stack.h

May 9th, 2020
1,239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. //
  2. // Created by Julio Tentor <jtentor@fi.unju.edu.ar>
  3. //
  4.  
  5. #ifndef DEMOSTACK2_STACK_H
  6. #define DEMOSTACK2_STACK_H
  7.  
  8. #include <stdexcept>
  9.  
  10. template <class Elemento>
  11. class stack {
  12. public:
  13.     stack(int capacidad = 10);
  14.     virtual ~stack();
  15.     void push(const Elemento elemento);
  16.     Elemento pop();
  17.     Elemento peek();
  18.     Elemento top() { return this->peek(); }
  19.     bool empty();
  20.     int count();
  21.  
  22. private:
  23.     int capacidad;
  24.     Elemento *datos;
  25.     int cuenta;
  26. };
  27.  
  28. template <class Elemento>
  29. stack<Elemento>::stack(int capacidad) {
  30.     this->capacidad = capacidad;
  31.     this->datos = new Elemento[this->capacidad];
  32.     this->cuenta = 0;
  33. }
  34.  
  35. template <class Elemento>
  36. stack<Elemento>::~stack() {
  37.     delete [] this->datos;
  38. }
  39.  
  40. template <class Elemento>
  41. void stack<Elemento>::push(const Elemento elemento) {
  42.     if (this->cuenta >= this->capacidad) {
  43.         throw std::runtime_error("ERROR La pila esta llena...");
  44.     }
  45.     this->datos[this->cuenta] = elemento;
  46.     ++this->cuenta;
  47. }
  48.  
  49. template <class Elemento>
  50. Elemento stack<Elemento>::pop() {
  51.     if (this->empty()) {
  52.         throw std::runtime_error("ERROR La pila esta vacía...");
  53.     }
  54.     --this->cuenta;
  55.     return this->datos[this->cuenta];
  56. }
  57.  
  58. template <class Elemento>
  59. Elemento stack<Elemento>::peek() {
  60.     if (this->empty()) {
  61.         throw std::runtime_error("ERROR La pila esta vacía...");
  62.     }
  63.     return this->datos[this->cuenta - 1];
  64. }
  65.  
  66. template <class Elemento>
  67. bool stack<Elemento>::empty() {
  68.     return this->cuenta <= 0;
  69. }
  70.  
  71. template <class Elemento>
  72. int stack<Elemento>::count() {
  73.     return this->cuenta;
  74. }
  75.  
  76.  
  77. #endif //DEMOSTACK2_STACK_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement