以下是使用了 <iostream> 头文件的完整代码:
#include <iostream>#include <vector>template<typename T, typename E>struct EdgeNode {int adjvex;E weight;EdgeNode<T, E> *next;};template<typename T, typename E>struct VertexNode {T data;EdgeNode<T, E> *firstEdge;};template<typename T, typename E>class GraphLink {private:std::vector<VertexNode<T, E>> vertexList; // 顶点数组public:void insertVertex(T data) {VertexNode<T, E> vNode;vNode.data = data;vNode.firstEdge = nullptr;vertexList.push_back(vNode);}void insertEdge(int startVex, int endVex, E weight) {EdgeNode<T, E> *newEdge1 = new EdgeNode<T, E>;newEdge1->adjvex = endVex;newEdge1->weight = weight;if (vertexList[startVex].firstEdge == nullptr) {vertexList[startVex].firstEdge = newEdge1;newEdge1->next = nullptr;} else {newEdge1->next = vertexList[startVex].firstEdge;vertexList[startVex].firstEdge = newEdge1;}}void disp() const {for (int i = 0; i < vertexList.size(); i++) {std::cout << "顶点" << i << "(" << vertexList[i].data << "): ";EdgeNode<T, E> *current = vertexList[i].firstEdge;while (current != nullptr) {std::cout << "-> [" << current->adjvex << "](" << current->weight << ")";current = current->next;}std::cout << std::endl;}}};int main() {GraphLink<char, int> G;G.insertVertex('A'); //0号G.insertVertex('B'); //1号G.insertVertex('C'); //2号G.insertVertex('D'); //3号G.insertVertex('E'); //4号G.insertEdge(0, 1, 1);G.insertEdge(1, 2, 2);G.insertEdge(2, 3, 10);G.insertEdge(2, 4, 2);G.insertEdge(4, 0, 4);G.disp();return 0;}
这个程序实现了一个基于邻接表的有向图数据结构,并提供了插入顶点和边以及展示图的功能。在主函数中,创建了一个包含5个顶点(A、B、C、D、E)的有向图,并插入了一些边,最后调用 disp() 方法展示图的信息。
内容由零声教学AI助手提供,问题来源于学员提问




