数据结构与算法学习库DSA
目录
数据结构与算法学习库——DSA
介绍
不少在校学生在学习数据结构与算法时痛苦不堪,很多数据结构写起来验证也很困难。如果有一个库,能帮助大家解决构建数据结构的困难,以快速验证自己的想法,那多好啊。
DSA(Data struct & Algorithm) 就是这样的一个工具。
示例 1
我们来看一个示例。
#include <iostream>
#include <string_view>
#include "binary_tree.h"
using namespace dsa;
using Tree = BinaryTree<int>;
int main() {
constexpr std::string_view tree_graph = R"(
1 <- right_rotate
/ \
2 3
/ \
4 5
||
2
/ \
4 1
/ \
5 3
)";
// We can build a binary tree from list
Tree tree({1, 2, 3, 4, 5});
std::cout << tree << std::endl;
// Rotate at root
tree.right_rotate(1);
// Print the tree
std::cout << tree << std::endl;
return 0;
}
只要引入头文件,
binary_tree.h
,你就能轻松的创建一个二叉树了。创建二叉树非常的简单,只需要提供一个数组就行了。它的构建规则就像 leetcode 中的示例构建规则。如果你要创建一下像下面的二叉树:
constexpr std::string_view tree_graph = R"(
2
/ \
4 1
/ \
5 3
)";
只需要调用:
Tree tree({2, 4, 1, {}, {}, 5, 3});
其中
{}, {}
表示用于占位节点 4 的两个空孩子节点,是不是非常简单。整个 list 相当于对二叉树进行层序遍历(空节点也需要遍历)。
当然二叉树非常非常简单,除此之外,你了可以引入
red_black_tree.h
,来构建红黑树,一切都是那么的自然。
如果你想验证自己的想法,比如想自己实现二叉树的一些基本操作,只需要继承
BinaryTree
就可以,像下面这样:
class MyBinaryTree : public BinaryTree<int> {
public:
// ...
};
示例 2
下面是红黑树的实现:
template <typename K, typename V>
class RedBlackTree : public BinarySearchTree<K, V> {
public:
// ...
};
使用起来也相当方便。
#include <vector>
#include <optional>
#include <red_black_tree.h>
using namespace dsa;
using Tree = RedBlackTree<int, int>;
int main() {
Tree tree;
for (int i = 10; i <= 100; i += 10) {
tree.insert(i, 2*i);
}
for (int i = 5; i <= 95; i += 10) {
tree.insert(i, 2*i);
}
std::cout << tree << std::endl << std::endl;
for (int i = 5; i <= 100; i += 5) {
tree.remove(i);
std::cout << "Remove:" << i << std::endl;
std::cout << tree << std::endl << std::endl;
}
return 0;
}
上面的程序会输出结果:
项目托管
本项目托管在
目前还在不断的完善中,欢迎有志之士帮助我们提 Issue,你也可以贡献自己的力量,来丰富这个项目。
联系方式
- QQ 群:610441700
- 钉钉群: