Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. template<class T>
  6. struct Node
  7. {
  8. T data;
  9. Node* next=nullptr;
  10. };
  11.  
  12. template<class T>
  13. class Stack
  14. {
  15. private:
  16. Node<T>* first=nullptr;
  17. public:
  18. void add_element(T data)
  19. {
  20. if(first==nullptr)
  21. {
  22. Node<T>* a = new Node<T>;
  23. a->data=data;
  24. first=a;
  25. }
  26. else
  27. {
  28. Node<T>* current=first;
  29. while(current->next!=nullptr)
  30. {
  31. current=current->next;
  32. }
  33. Node<T>* a = new Node<T>;
  34. a->data=data;
  35. current->next=a;
  36. }
  37. }
  38. T peak()
  39. {
  40. Node<T>* current=first;
  41. while(current->next!=nullptr)
  42. {
  43. current=current->next;
  44. }
  45. return current->data;
  46. }
  47. void pop()
  48. {
  49. Node<T>* current=first;
  50. if(current->next==nullptr)
  51. {
  52. delete current->next;
  53. current->next=nullptr;
  54. }
  55. else
  56. {
  57. while(current->next->next!=nullptr)
  58. {
  59. current=current->next;
  60. }
  61. delete current->next;
  62. current->next=nullptr;
  63. }
  64. }
  65. void print()
  66. {
  67. Node<T>* current=first;
  68. while(current!=nullptr)
  69. {
  70. cout<<current->data;
  71. current=current->next;
  72. }
  73. }
  74.  
  75. };
  76.  
  77. int main()
  78. {
  79. Stack<char> s;
  80. s.add_element('(');
  81. s.add_element(')');
  82. s.print();
  83. cout<<s.peak();
  84. s.pop();
  85. s.print();
  86. return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement