Advertisement
Infiniti_Inter

с74, №19(my stack)

Apr 11th, 2019
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4. #include <exception>
  5.  
  6. #define myStack
  7. #define myAlg
  8.  
  9. using namespace std;
  10.  
  11.  
  12.  
  13. #ifdef myStack
  14. template<class T>
  15. class Stack {
  16.  
  17. struct Node {
  18.    
  19.     Node(T el, Node * node)
  20.     {
  21.         data = el;
  22.         next = node;
  23.     }
  24.     Node* next;
  25.     T data;
  26. }; 
  27.  
  28. Node* _top;
  29. int _size;
  30.    
  31. public:
  32.     Stack()
  33.     {
  34.         _top = NULL;
  35.         _size = 0;
  36.     }
  37.     ~Stack()
  38.     {
  39.         while (_top != NULL && _top->next != NULL)
  40.         {
  41.             Node* temp = _top;
  42.             _top = _top->next;
  43.             delete temp;
  44.         }
  45.     }
  46.  
  47.     void push(T el);
  48.     void pop();
  49.     T top();
  50.     int size();
  51.     T peek();
  52.  
  53.     bool empty();
  54.  
  55. };
  56. #endif
  57. #ifdef myAlg
  58. template<class T>
  59. bool Stack<T>::empty()
  60. {
  61.     return !_size;
  62. }
  63.  
  64. template<class T>
  65. T Stack<T>::peek()
  66. {
  67.     if (!_size)
  68.         return NULL;
  69.     return _top->data;
  70. }
  71.  
  72. template<class T>
  73. int Stack<T>::size()
  74. {
  75.     return _size;
  76. }
  77. template<class T>
  78.  
  79. T Stack<T>::top()
  80. {
  81.     try
  82.     {
  83.         if (_top == NULL)
  84.             throw out_of_range("Error: Stack is empty!");
  85.         return _top->data;
  86.     }
  87.     catch (exception &e)
  88.     {
  89.         cout << e.what() << endl;
  90.     }
  91. }
  92.  
  93. template<class T>
  94. void Stack<T>::pop() {
  95.     Node* temp = _top;
  96.     _top = _top->next;
  97.     delete temp;
  98.     _size--;
  99.  
  100. }
  101. template<class T>
  102. void Stack<T>::push(T el)
  103. {
  104.     Node * temp = new Node(el, _top);
  105.     _top = temp;
  106.     _size++;
  107. }
  108. #endif // myStack
  109.  
  110.  
  111. int main()
  112. {
  113.  
  114.     Stack<string> words;
  115.  
  116.     fstream file("words.txt", ios::in);
  117.     while (file.peek() != EOF)
  118.     {
  119.         string s;
  120.         file >> s;
  121.         words.push(s);
  122.     }
  123.     //cout << words.size();
  124.     while (!words.empty()){
  125.         string s;
  126.         s = words.top();
  127.         words.pop();
  128.         cout << s << endl;
  129.         if (s.length() == 1)
  130.             cout << s << endl;
  131.     }
  132.     return 0;
  133. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement