mirror of
https://gitee.com/mirrors_PX4/PX4-Autopilot.git
synced 2026-07-18 17:10:35 +08:00
Linked list: optimized insertBefore(), elaborated docs
This commit is contained in:
@@ -57,19 +57,22 @@ public:
|
||||
unsigned getLength() const;
|
||||
|
||||
/**
|
||||
* Complexity: O(N) (calls remove())
|
||||
* Inserts the node to the beginning of the list.
|
||||
* If the node is already present in the list, it will be relocated to the beginning.
|
||||
* Complexity: O(N)
|
||||
*/
|
||||
void insert(T* node);
|
||||
|
||||
/**
|
||||
* Inserts the node immediately before the node B where
|
||||
* predicate(B) -> true.
|
||||
* Inserts the node immediately before the node X where predicate(X) returns true.
|
||||
* If the node is already present in the list, it can be relocated to a new position.
|
||||
* Complexity: O(2N) (calls remove())
|
||||
*/
|
||||
template <typename Predicate>
|
||||
void insertBefore(T* node, Predicate predicate);
|
||||
|
||||
/**
|
||||
* Removes only the first occurence of the node.
|
||||
* Complexity: O(N)
|
||||
*/
|
||||
void remove(const T* node);
|
||||
@@ -107,11 +110,17 @@ template <typename Predicate>
|
||||
void LinkedListRoot<T>::insertBefore(T* node, Predicate predicate)
|
||||
{
|
||||
UAVCAN_ASSERT(node);
|
||||
if (node == NULL)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
remove(node);
|
||||
|
||||
if (root_ == NULL || predicate(root_))
|
||||
{
|
||||
insert(node);
|
||||
node->setNextListNode(root_);
|
||||
root_ = node;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -104,11 +104,27 @@ TEST(LinkedList, Sorting)
|
||||
uavcan::LinkedListRoot<ListItem> root;
|
||||
ListItem items[] = {0, 1, 2, 3, 4, 5};
|
||||
|
||||
EXPECT_EQ(0, root.getLength());
|
||||
|
||||
items[2].insort(root);
|
||||
EXPECT_EQ(1, root.getLength());
|
||||
|
||||
items[2].insort(root); // Making sure the duplicate will be removed
|
||||
EXPECT_EQ(1, root.getLength());
|
||||
|
||||
items[3].insort(root);
|
||||
|
||||
items[0].insort(root);
|
||||
|
||||
items[4].insort(root);
|
||||
EXPECT_EQ(4, root.getLength());
|
||||
|
||||
items[1].insort(root);
|
||||
EXPECT_EQ(5, root.getLength());
|
||||
|
||||
items[1].insort(root); // Another duplicate
|
||||
EXPECT_EQ(5, root.getLength());
|
||||
|
||||
items[5].insort(root);
|
||||
|
||||
EXPECT_EQ(6, root.getLength());
|
||||
|
||||
Reference in New Issue
Block a user