Guest User

Untitled

a guest
Nov 13th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5.  
  6. template <typename T>
  7. class Node {
  8. public:
  9. T value;
  10. class Node *next;
  11. };
  12.  
  13. template <typename T>
  14. class Stack {
  15. private:
  16. class Node<T> *top = nullptr;
  17.  
  18. public:
  19. void push(const T);
  20. T pop();
  21. void display();
  22. };
  23.  
  24. template <typename T>
  25. void Stack<T>::push(const T value) {
  26. Node<T> *newNode = new Node<T>;
  27. newNode->value = value;
  28. newNode->next = top;
  29. top = newNode;
  30. }
  31.  
  32. template <typename T>
  33. T Stack<T>::pop() {
  34. if (top != nullptr) {
  35. cout << "Empty stack!" << endl;
  36. return 0;
  37. }
  38.  
  39. Node<T> *temp = top;
  40. T value = temp->value;
  41. top = top->next;
  42. delete temp;
  43. return value;
  44. }
  45.  
  46. template <typename T>
  47. void Stack<T>::display() {
  48. Node<T> *temp = top;
  49.  
  50. cout << "----------" << endl;
  51. while (temp != nullptr) {
  52. cout << temp->value << endl;
  53. temp = temp->next;
  54. }
  55. cout << "----------" << endl;
  56. }
  57.  
  58. void main()
  59. {
  60. Stack<int> stack;
  61. stack.push(3);
  62. stack.push(5);
  63. stack.display();
  64. for (int i = 0; i < 10; i++)
  65. {
  66. stack.push(i);
  67. }
  68. stack.display();
  69. cout << "Deleted: " << stack.pop() << endl;
  70. cout << "Deleted: " << stack.pop() << endl;
  71. stack.display();
  72.  
  73. system("pause");
  74. }
Add Comment
Please, Sign In to add comment