jubilant-funicular
LinkedNode.h
1 #ifndef NTA_LINKEDNODE_H_INCLUDED
2 #define NTA_LINKEDNODE_H_INCLUDED
3 
4 #include <functional>
5 
6 #include "nta/MyEngine.h"
7 
8 namespace nta {
9  namespace utils {
11  // Why not use std::forward_list? Because I forgot it existed...
12  template<typename T>
13  struct LinkedNode {
15  class iterator {
16  public:
17  using value_type = T;
18  using difference_type = std::ptrdiff_t;
19  using pointer = T*;
20  using reference = T&;
21  using iterator_category = std::forward_iterator_tag;
22  private:
23  LinkedNode* m_node;
24  public:
25  iterator() {}
26  iterator(LinkedNode* node) : m_node(node) {}
27  reference operator*() const {
28  return m_node->data;
29  }
30  pointer operator->() const {
31  return &m_node->data;
32  }
33  iterator& operator++() {
34  m_node = m_node->next;
35  return *this;
36  }
37  iterator operator++(int) {
38  auto ret = *this;
39  operator++();
40  return ret;
41  }
42  bool operator==(const iterator& rhs) const {
43  return m_node == rhs.m_node;
44  }
45  bool operator!=(const iterator& rhs) const {
46  return !operator==(rhs);
47  }
48  };
49 
50  LinkedNode(T d) : data(d) {}
51  LinkedNode(T d, LinkedNode* nxt) : next(nxt), data(d) {}
52  ~LinkedNode() { if (next) delete next; next = nullptr; }
53 
54  iterator begin() {
55  return iterator(this);
56  }
57  iterator end() {
58  return iterator(nullptr);
59  }
60 
61  std::size_t size() const {
62  std::size_t len = 0;
63  const LinkedNode* curr = this;
64  while (curr && ++len) curr = curr->next;
65  return len;
66  }
67 
68  static void remove(LinkedNode*& head, T d) {
69  LinkedNode** curr = &head;
70  while ((*curr) && (*curr)->data != d) {
71  curr = &(*curr)->next;
72  }
73  if (*curr) *curr = (*curr)->next;
74  }
75  static void remove(LinkedNode*& node) {
76  if (node) node = node->next;
77  }
79  static bool remove(LinkedNode*& head, std::function<bool(const T&)> pred) {
80  LinkedNode** curr = &head;
81  while (*curr && !pred((*curr)->data)) {
82  curr = &(*curr)->next;
83  }
84  if (*curr) {
85  *curr = (*curr)->next;
86  return true;
87  }
88  return false;
89  }
90 
92  LinkedNode* next = nullptr;
94  T data;
95  };
96  }
97 }
98 
99 #endif // NTA_LINKEDNODE_H_INCLUDED
nta::utils::LinkedNode::next
LinkedNode * next
The next node in the linked list.
Definition: LinkedNode.h:92
nta::utils::LinkedNode
A generic linked list.
Definition: LinkedNode.h:13
nta
Definition: Animation2D.h:6
nta::utils::LinkedNode::iterator
Custom iterator for looping over the data in the linked list.
Definition: LinkedNode.h:15
nta::utils::LinkedNode::remove
static bool remove(LinkedNode *&head, std::function< bool(const T &)> pred)
returns true on success
Definition: LinkedNode.h:79
nta::utils::LinkedNode::data
T data
The (pointer to the) data associated to this node.
Definition: LinkedNode.h:94