Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "Stack.h"
- // Note: if you get an error about nullptr, try using -std=c++0x commandline switch
- // or whatever compiler switch forces C++11 standard compiling (-std=c++0x is for g++).
- // Stack class
- template<class T>
- Stack<T>::Stack()
- {
- top = nullptr; //10
- }
- // Push
- template<class T>
- void Stack<T>::push(T newItem)
- {
- StackNode<T> *newNode = new StackNode<T>(newItem, top); //17 - top is a private pointer for the class Stack class (header)
- top = newNode; //18
- }
- // Peek
- template<class T>
- T Stack<T>::peek()
- {
- if (!isEmpty()) return top ->getData(); //try to avoid checking for nullptr.
- }
- // Pop
- template<class T>
- T Stack<T>::pop()
- {
- T data = peek(); //local variable of type T called data
- StackNode<T> *temp = top; //if top is not empty, want to be able to remove it.
- if (!isEmpty())
- {
- top = top ->getNext(); //top becomes top's next
- delete temp; //delete the original top data.
- }
- return data;
- }
- // isEmpty
- template<class T>
- bool Stack<T>::isEmpty()
- {
- return top == nullptr; //if top is not nullptr, then returns falls. is empty? returns true.
- }
- // clear
- template<class T>
- void Stack<T>::clear()
- {
- StackNode<T> *current = top; //traversal woo
- if (current == nullptr)
- {
- std::cout << "Stack is empty, nothing to clear." << std::endl;
- }
- else
- {
- while (current != nullptr) //while current is not a null value
- {
- StackNode<T> *temp = current;
- current = current->getNext();
- delete temp;
- }
- }
- }
- // display stack contents
- template<class T>
- void Stack<T>::display()
- {
- StackNode<T> *current = top;
- if (current == nullptr)
- {
- std::cout << "Stack is empty, nothing to display." << std::endl;
- }
- else
- {
- std::cout << "T: ";
- while (current != nullptr)
- {
- std::cout << "{" << current->getData() << "}";
- current = current->getNext();
- }
- std::cout << std::endl;
- }
- }
Add Comment
Please, Sign In to add comment