Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- template <typename ElemT>
- class ListFw
- {
- public:
- class Node
- {
- public:
- ElemT data;
- Node* next;
- Node(const ElemT& dataP, Node* nextP = nullptr)
- :data{ dataP }, next{ nextP }{};
- };
- private:
- Node* head;
- Node* tail;
- size_t size;
- public:
- ListFw() : head{ nullptr }, tail{ nullptr }, size{ 0 } {}
- ElemT& front() { return head->data; };
- const ElemT& front()const { return head->data; };
- ElemT& back() { return tail->data; };
- const ElemT& back()const { return tail->data; };
- const size_t getSize() const { return size; };
- bool empty() const { return size == 0; };
- void push_back(const ElemT& data);
- void push_front(const ElemT& data);
- bool pop_back();
- bool pop_front();
- void clear();
- ~ListFw();
- };
- template <typename ElemT>
- void ListFw<ElemT>::push_back(const ElemT& data)
- {
- if (!head)
- {
- head = new Node{ data };
- tail = head;
- }
- else
- {
- tail->next = new Node{ data };
- tail = tail->next;
- }
- ++size;
- }
- template <typename ElemT>
- void ListFw<ElemT>::push_front(const ElemT& data)
- {
- head = new Node{ data, head };
- ++size;
- if (!tail)
- {
- tail = head;
- }
- }
- template <typename ElemT>
- bool ListFw<ElemT>::pop_front()
- {
- if (head)
- {
- Node* tmp{ head };
- head = head->next;
- delete tmp;
- --size;
- return true;
- }
- return false;
- }
- template <typename ElemT>
- bool ListFw<ElemT>::pop_back()
- {
- if (tail)
- {
- if (tail == head)
- {
- delete tail;
- size = 0;
- tail = nullptr;
- head = nullptr;
- return true;
- }
- for (Node* curr{ head }; curr; curr = curr->next)
- {
- if (curr->next == tail)
- {
- delete tail;
- curr->next = nullptr;
- tail = curr;
- --size;
- return true;
- }
- }
- }
- return false;
- }
- template <typename ElemT>
- void ListFw<ElemT>::clear()
- {
- while (tail)
- {
- std::cout << "Clear for: " << front() << '\n';
- pop_front();
- }
- }
- template <typename ElemT>
- ListFw<ElemT>::~ListFw()
- {
- while (head)
- {
- std::cout << "Destruct for: " << front() << '\n';
- pop_front();
- }
- }
- template <typename ElemT>
- class Stack
- {
- ListFw<ElemT> storage;
- public:
- Stack() : storage{} {};
- bool empty() { return !storage.getSize(); };
- size_t size() { return storage.getSize(); };
- ElemT top() { return storage.front(); };
- void push(const ElemT& elem) { storage.push_front(elem); };
- void pop() { storage.pop_front(); };
- };
- int main()
- {
- Stack<int> stack;
- for (int i{ 0 }; i < 10; ++i)
- {
- stack.push(i);
- };
- while (!stack.empty())
- {
- std::cout << stack.top() << '\n';
- stack.pop();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement