// // Created by 31416 on 24-12-4. // #ifndef GRAPH_H #define GRAPH_H #include #include "GraphExceptions/NodeIdOutOfRangeException.h" #include "GraphExceptions/SameNodeConnectException.h" using namespace std; /* * 简述: * 节点=数据域+指针域 * 第一个节点存储id * 第二个节点存储值 * 后续节点存储连接关系 * 数据域: * data:可存id,可存其他节点的id,可存数据 * weight:边上的权 */ template class Graph { private: struct node{ T data; T weight; struct node* next; }; vector nodes; int max_size; public: Graph() { nodes.clear(); max_size = 0; } void insert(T data) { max_size++; node* insert = new node(); insert->data=max_size; insert->weight = 0; insert->next=new node(); insert->next->data=data; insert->next->next=NULL; nodes.push_back(insert); } void connect(int id1,int id2,bool flag,T weight=0) { //flag区分是否为有向图 if(id1==id2) { throw SameNodeConnectException("禁止连接图中的同一个点",0x001); } if ((id1>max_size||id2>max_size)||(id1<0)||(id2<0)) { throw NodeIdOutOfRangeException("您提供的id超出范围",0X002); } node *current = nodes.at(id1); while(current->next!=NULL) { current = current->next; } current->next=new node(); current->next->data=id2; current->next->weight = weight; current->next->next=NULL; if (flag==false) { node *current = nodes.at(id2); while(current->next!=NULL) { current = current->next; } current->next=new node(); current->next->data=id1; current->next->weight = weight; current->next->next=NULL; } } }; #endif //GRAPH_H