Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef STACK_LINKED_LIST
- #define STACK_LINKED_LIST
- #include<iostream>
- template<typename T>
- struct StackElement
- {
- T data;
- StackElement<T>* link;
- };
- template<typename T>
- class StackList
- {
- public:
- StackList() : topElement(nullptr) {};
- ~StackList();
- StackList(const StackList<T>& other);
- StackList<T>& operator=(const StackList<T>& other);
- void push(const T& element);
- bool empty() const;
- T top() const;
- T pop();
- //friend std::istream& operator>>(std::istream& in, StackList<T> stack);
- friend std::ostream& operator<<(std::ostream& out, StackList<T> stack);
- private:
- StackElement<T>* topElement;
- void copy(StackElement<T>* other);
- void deleteStack();
- void copyStack(const StackList<T>& other);
- };
- template<typename T>
- std::ostream& operator<<(std::ostream& out, StackList<T> stack)
- {
- while (!stack.empty())
- {
- T x = stack.pop();
- out << x << " ";
- }
- return out;
- }
- template<typename T>
- bool StackList<T>::empty() const
- {
- return topElement == nullptr;
- }
- template<typename T>
- void StackList<T>::push(const T& element)
- {
- StackElement<T>* newElementPtr = new StackElement<T>;
- newElementPtr->data = element;
- newElementPtr->link = topElement;
- topElement = newElementPtr;
- }
- template<typename T>
- T StackList<T>::pop()
- {
- if (empty())
- {
- std::cerr << "Cannot pop from an empty stack" << std::endl;
- return T();
- }
- StackElement<T>* tempElement = topElement;
- topElement = topElement->link;
- T x = tempElement->data;
- delete tempElement;
- return x;
- }
- template<typename T>
- T StackList<T>::top() const
- {
- if (empty())
- {
- std::cerr << "Cannot get an element from an empty stack." << std::endl;
- return T();
- }
- return topElement->data;
- }
- template<typename T>
- void StackList<T>::deleteStack()
- {
- while (!empty())
- pop();
- }
- template<typename T>
- StackList<T>::~StackList()
- {
- deleteStack();
- }
- template<typename T>
- void StackList<T>::copy(StackElement<T>* element)
- {
- if (element == nullptr)
- return;
- copy(element->link);
- push(element->data);
- }
- template<typename T>
- void StackList<T>::copyStack(const StackList<T>& other)
- {
- topElement = nullptr;
- copy(other.topElement);
- }
- template<typename T>
- StackList<T>::StackList(const StackList<T>& other)
- {
- copyStack(other);
- }
- template<typename T>
- StackList<T>& StackList<T>::operator=(const StackList<T>& other)
- {
- if (this != &other)
- {
- deleteStack();
- copyStack(other);
- }
- return *this;
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement