Files
data-structures-and-algorithms/homework5/Graph.h
T

81 lines
1.9 KiB
C++

//
// Created by 31416 on 24-12-4.
//
#ifndef GRAPH_H
#define GRAPH_H
#include<vector>
#include "GraphExceptions/NodeIdOutOfRangeException.h"
#include "GraphExceptions/SameNodeConnectException.h"
using namespace std;
/*
* 简述:
* 节点=数据域+指针域
* 第一个节点存储id
* 第二个节点存储值
* 后续节点存储连接关系
* 数据域:
* data:可存id,可存其他节点的id,可存数据
* weight:边上的权
*/
template<typename T>
class Graph {
private:
struct node{
T data;
T weight;
struct node* next;
};
vector<node> 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;
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