Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef LIST_H
- #define LIST_H value
- #include <memory>
- #include <iostream>
- template <bool flag, class IsTrue, class IsFalse>
- struct choose;
- template <class IsTrue, class IsFalse>
- struct choose<true, IsTrue, IsFalse> {
- typedef IsTrue type;
- };
- template <class IsTrue, class IsFalse>
- struct choose<false, IsTrue, IsFalse> {
- typedef IsFalse type;
- };
- /* using shared_ptr = std::shared_ptr; */
- using namespace std;
- /**
- * Singly linked list
- */
- template<typename D>
- class List {
- struct Node {
- shared_ptr<D> data;
- Node* next;
- Node* prev;
- Node(shared_ptr<D> d, Node* p, Node* n) : data(d), prev(p), next(n) {}
- ~Node() {
- data.reset();
- delete next;
- }
- };
- /**
- * Iterator structure for this list
- */
- template <bool isconst = false>
- struct iterator : public std::iterator<std::forward_iterator_tag, shared_ptr<D>> {
- typedef std::forward_iterator_tag iterator_category;
- typedef shared_ptr<D> value_type;
- typedef std::ptrdiff_t Distance;
- typedef typename choose<isconst, const value_type&, value_type&>::type
- Reference;
- typedef typename choose<isconst, const value_type*, value_type*>::type
- Pointer;
- typedef typename choose<isconst, const Node*, Node*>::type
- nodeptr;
- iterator(nodeptr x = nullptr) : curr_node(x) {}
- iterator(const iterator<false>& i) : curr_node(i.curr_node) {}
- Reference operator*() const { return curr_node->data; }
- Pointer operator->() const { return &(curr_node->data); }
- template<bool A>
- friend bool operator==(const iterator<A>& a, const iterator<A>& b) {
- return a.curr_node == b.curr_node;
- }
- template<bool A>
- friend bool operator!=(const iterator<A>& a, const iterator<A>& b) {
- return !(a.curr_node == b.curr_node);
- }
- friend class List<D>;
- iterator& operator++() {
- curr_node = curr_node->next;
- return *this;
- }
- private:
- nodeptr curr_node;
- };
- public:
- /**
- * Create a new empty list
- */
- List();
- int len() const;
- ~List();
- /**
- * allows us to stream the list
- */
- std::ostream& dump(std::ostream &strm) const {
- for (const auto s : *this) {
- strm << *s << std::endl;
- }
- return strm;
- }
- /**
- * iterator methods
- */
- iterator<false> begin() {
- return iterator<false>(head);
- }
- iterator<false> end() {
- return iterator<false>(nullptr);
- }
- iterator<true> begin() const {
- return iterator<true>(head);
- }
- iterator<true> end() const {
- return iterator<true>(nullptr);
- }
- private:
- Node* head;
- };
- template<typename D>
- List<D>::List() {
- head = nullptr;
- }
- template<typename D>
- int List<D>::len() const {
- int ret = 0;
- for (const auto& n : *this) {
- ret++;
- }
- return ret;
- }
- template<typename D>
- List<D>::~List() {
- delete this->head;
- }
- #endif /* ifndef LIST_H */
Add Comment
Please, Sign In to add comment