创建邻接表存储图的信息代码
时间: 2023-12-03 14:44:30 浏览: 63
以下是使用邻接表存储图的示例代码,其中使用了C++语言:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 邻接表存储图节点信息
struct GraphNode {
int val; // 节点值
vector<GraphNode*> neighbors; // 存储相邻节点的指针
GraphNode(int x) : val(x) {};
};
int main() {
// 创建图节点
GraphNode* node1 = new GraphNode(1);
GraphNode* node2 = new GraphNode(2);
GraphNode* node3 = new GraphNode(3);
GraphNode* node4 = new GraphNode(4);
// 设置节点之间的关系
node1->neighbors.push_back(node2);
node1->neighbors.push_back(node4);
node2->neighbors.push_back(node1);
node2->neighbors.push_back(node3);
node3->neighbors.push_back(node2);
node3->neighbors.push_back(node4);
node4->neighbors.push_back(node1);
node4->neighbors.push_back(node3);
// 输出节点及其相邻节点信息
cout << "节点1相邻节点: ";
for (auto neighbor : node1->neighbors) {
cout << neighbor->val << " ";
}
cout << endl;
cout << "节点2相邻节点: ";
for (auto neighbor : node2->neighbors) {
cout << neighbor->val << " ";
}
cout << endl;
cout << "节点3相邻节点: ";
for (auto neighbor : node3->neighbors) {
cout << neighbor->val << " ";
}
cout << endl;
cout << "节点4相邻节点: ";
for (auto neighbor : node4->neighbors) {
cout << neighbor->val << " ";
}
cout << endl;
return 0;
}
```
运行结果如下:
```
节点1相邻节点: 2 4
节点2相邻节点: 1 3
节点3相邻节点: 2 4
节点4相邻节点: 1 3
```
以上代码使用了vector来存储相邻节点的指针,这是因为vector的大小是可变的,可以动态地添加和删除元素。同时,vector的访问速度也比较快,可以提高程序的效率。
阅读全文