// #pragma once #ifndef LIST_HPP #define LIST_HPP #include #include #include namespace ecci { class List { private: struct Node { public: Node* previous; std::string data; Node* next; public: explicit Node(const std::string& data, Node* previous = nullptr , Node* next = nullptr) : previous(previous) , data(data) , next(next) { } }; private: size_t count; Node* first; // head Node* last; // tail public: // Construction, copy, and destruction /// Default constructor List() : count(0) , first(nullptr) , last(nullptr) { } /// Destructor ~List() { this->clear(); } public: // Accessors inline bool isEmpty() const { return this->first == nullptr; } inline bool operator!() const { return this->isEmpty(); } // inline operator bool() const { return !this->isEmpty(); } inline size_t getCount() const { return this->count; } public: // Insertion, removal void append(const std::string& data) { if (this->isEmpty()) { this->first = this->last = new Node(data); if (this->isEmpty()) { throw std::runtime_error("list: no memory to append node"); } } else { this->last->next = new Node(data, this->last); if (this->last->next == nullptr) { throw std::runtime_error("list: no memory to append node"); } this->last = this->last->next; } ++this->count; } /// Empties the list from last element to the fisrt one void clear() { while (this->last) { Node* const current = this->last; this->last = this->last->previous; delete current; } this->first = nullptr; this->count = 0; } public: // friend std::ostream& operator<<(std::ostream& out, const List& list) { // for (const Node* node = list.first; node; node = node->next) { // out << node->data << std::endl; // } // return out; // } class ConstIterator { private: Node* node; public: explicit ConstIterator(Node* node) : node(node) { } /// Returns true if two iterators point to the same element inline bool operator!=(const ConstIterator& other) const { return this->node != other.node; } /// Get access to the pointed data. Iterator must no be end() inline const std::string& operator*() const { return this->node->data; } /// Moves to the next element. Must not be end() inline ConstIterator& operator++() { this->node = this->node->next; return *this; } /// Moves to the next element. Must not be end() inline ConstIterator operator++(int) { ConstIterator result(*this); this->node = this->node->next; return result; } }; /// Get access to the first element // Iterator begin(); inline ConstIterator begin() const { return ConstIterator(this->first); } /// Returns a no valid position inline ConstIterator end() const { return ConstIterator(nullptr); } }; } // namespace ecci #endif // LIST_HPP