Hollowfires

Untitled

Apr 21st, 2018
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. #include "Stack.h"
  2.  
  3.  
  4. // Note: if you get an error about nullptr, try using -std=c++0x commandline switch
  5. // or whatever compiler switch forces C++11 standard compiling (-std=c++0x is for g++).
  6.  
  7. // Stack class
  8. template<class T>
  9. Stack<T>::Stack()
  10. {
  11. top = nullptr; //10
  12. }
  13.  
  14. // Push
  15. template<class T>
  16. void Stack<T>::push(T newItem)
  17. {
  18. StackNode<T> *newNode = new StackNode<T>(newItem, top); //17 - top is a private pointer for the class Stack class (header)
  19. top = newNode; //18
  20. }
  21.  
  22. // Peek
  23. template<class T>
  24. T Stack<T>::peek()
  25. {
  26. if (!isEmpty()) return top ->getData(); //try to avoid checking for nullptr.
  27. }
  28.  
  29. // Pop
  30. template<class T>
  31. T Stack<T>::pop()
  32. {
  33. T data = peek(); //local variable of type T called data
  34. StackNode<T> *temp = top; //if top is not empty, want to be able to remove it.
  35. if (!isEmpty())
  36. {
  37. top = top ->getNext(); //top becomes top's next
  38. delete temp; //delete the original top data.
  39. }
  40. return data;
  41. }
  42.  
  43. // isEmpty
  44. template<class T>
  45. bool Stack<T>::isEmpty()
  46. {
  47. return top == nullptr; //if top is not nullptr, then returns falls. is empty? returns true.
  48. }
  49.  
  50. // clear
  51. template<class T>
  52. void Stack<T>::clear()
  53. {
  54.  
  55. StackNode<T> *current = top; //traversal woo
  56.  
  57. if (current == nullptr)
  58. {
  59. std::cout << "Stack is empty, nothing to clear." << std::endl;
  60. }
  61. else
  62. {
  63. while (current != nullptr) //while current is not a null value
  64. {
  65. StackNode<T> *temp = current;
  66. current = current->getNext();
  67. delete temp;
  68. }
  69. }
  70. }
  71.  
  72. // display stack contents
  73. template<class T>
  74. void Stack<T>::display()
  75. {
  76. StackNode<T> *current = top;
  77. if (current == nullptr)
  78. {
  79. std::cout << "Stack is empty, nothing to display." << std::endl;
  80. }
  81. else
  82. {
  83. std::cout << "T: ";
  84.  
  85. while (current != nullptr)
  86. {
  87. std::cout << "{" << current->getData() << "}";
  88. current = current->getNext();
  89. }
  90.  
  91. std::cout << std::endl;
  92. }
  93. }
Add Comment
Please, Sign In to add comment