与此示例类似:
我想如图所示进行链接列表节点连接,但是我被卡住了,我应该如何进行?
class Node{
public:
int id;
int count;
int *next;
int *prev;
Node(int a): id(a), count(0), next(NULL), prev(NULL) {};
Node(const int & ss, const int &c): id(ss), count( c), next(NULL), prev(NULL) {};
现在,我有了这些以及其他一些setter和getter函数。
最佳答案
该图片是graph adjacency list,其中:
Node* adjacency_list[5]
足以代表这一点。工作示例:
#include <iostream>
class Node {
public:
int id;
Node *next;
Node *prev;
Node(int a): id(a), next(0), prev(0) {}
};
Node* make_list(std::initializer_list<int> ids) {
Node* head = 0;
Node** ptail = &head;
for(int id : ids) {
*ptail = new Node(id - 1);
ptail = &((**ptail).next);
}
return head;
}
void print_list(Node** heads, int count) {
for(int i = 0; i < count; ++i) {
std::cout << (i + 1) << ": ";
for(Node* n = heads[i]; n; n = n->next)
std::cout << (n->id + 1) << ',';
std::cout << '\n';
}
}
int main() {
Node* adjacency_list[5] = {};
adjacency_list[1 - 1] = make_list({2, 3, 4});
adjacency_list[2 - 1] = make_list({4, 5});
adjacency_list[3 - 1] = make_list({1, 2, 5});
adjacency_list[4 - 1] = make_list({5});
adjacency_list[5 - 1] = make_list({4});
print_list(adjacency_list, 5);
}
输出:
1: 2,3,4,
2: 4,5,
3: 1,2,5,
4: 5,
5: 4,
在实际的应用程序中,您可能想要确保分配的内存不会泄漏(在本示例中为泄漏),或者使用
std::forward_list
或其他标准或第三方容器。
关于c++ - 如何在一个节点指向多个其他注释的地方创建链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61129890/