List container improvements and testing

- support range based for loops
 - add remove() method to remove a node
 - add clear() to empty entire list and delete nodes
 - add empty() helper
This commit is contained in:
Daniel Agar
2019-03-01 21:01:04 -05:00
parent 6c3e79f361
commit e2bf4b1894
15 changed files with 335 additions and 88 deletions
+84 -2
View File
@@ -1,6 +1,6 @@
/****************************************************************************
*
* Copyright (C) 2012 PX4 Development Team. All rights reserved.
* Copyright (C) 2012-2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -34,11 +34,13 @@
/**
* @file List.hpp
*
* A linked list.
* An intrusive linked list.
*/
#pragma once
#include <stdlib.h>
template<class T>
class ListNode
{
@@ -64,8 +66,88 @@ public:
_head = newNode;
}
bool remove(T removeNode)
{
// base case
if (removeNode == _head) {
_head = nullptr;
return true;
}
for (T node = getHead(); node != nullptr; node = node->getSibling()) {
// is sibling the node to remove?
if (node->getSibling() == removeNode) {
// replace sibling
if (node->getSibling() != nullptr) {
node->setSibling(node->getSibling()->getSibling());
} else {
node->setSibling(nullptr);
}
return true;
}
}
return false;
}
struct Iterator {
T node;
Iterator(T v) : node(v) {}
operator T() const { return node; }
operator T &() { return node; }
T operator* () const { return node; }
Iterator &operator++ ()
{
if (node) {
node = node->getSibling();
};
return *this;
}
};
Iterator begin() { return Iterator(getHead()); }
Iterator end() { return Iterator(nullptr); }
const T getHead() const { return _head; }
bool empty() const { return getHead() == nullptr; }
size_t size() const
{
size_t sz = 0;
for (auto node = getHead(); node != nullptr; node = node->getSibling()) {
sz++;
}
return sz;
}
void deleteNode(T node)
{
if (remove(node)) {
// only delete if node was successfully removed
delete node;
}
}
void clear()
{
auto node = getHead();
while (node != nullptr) {
auto next = node->getSibling();
delete node;
node = next;
}
_head = nullptr;
}
protected:
T _head{nullptr};