As I know it is not good idea to have so many pointers in c++ code. But I have written this simple implementation of linked list in c++ and there are many pointers in it, how can I improve that? Also as I tried I can not use functions in algorithm module on this linked list, how can I make this class compatible with those?
template <typename T>
class linkedlist {
private:
struct node {
node() : T() {
}
node(node * prev, node * next, const T & data) :
prev(prev), next(next), data(data) {
}
node * next;
node * prev;
T data = T();
};
node first;
node last;
public:
linkedlist() :
first(nullptr, &last, T()),
last(&first, &last, T()) {
}
class iterator {
friend class linkedlist;
private:
node * current_node;
public:
iterator(node * current_node) : current_node(current_node) {
}
T & operator*() {
return current_node->data;
}
const T & operator*() const {
return current_node->data;
}
iterator & operator++() {
current_node = current_node->next;
return *this;
}
bool operator!=(const iterator & other) {
return current_node != other.current_node;
}
};
void add(const T & data) {
node * new_node = new node(last.prev, &last, data);
new_node->prev->next = new_node;
new_node->next->prev = new_node;
}
bool remove(iterator & iterator) {
if (iterator.current_node == &first || iterator.current_node == &last)
return false;
node *to_remove = iterator.current_node;
to_remove->prev->next = to_remove->next;
to_remove->next->prev = to_remove->prev;
delete to_remove;
return true;
}
iterator begin() {
return iterator(first.next);
}
iterator end() {
return iterator(&last);
}
iterator find(const T & data) {
for (iterator it = begin(); it != end(); ++it) {
if (*it == data) {
return it;
}
}
return end();
}
};
algorithm
? Certain algorithms require certain iterator traits (for example,std::partition
requires a Bidirectional Iterator). In your case, you could only use algorithms that work with at most a ForwardIterator (as your iterator can only move forward). See this chart for more info: cplusplus.com/reference/iterator Also, pointers by themselves are not bad; it's how you (ab)use them that's usually the problem. \$\endgroup\$find
and it didn't worked, thank you for the link :-) \$\endgroup\$