156 lines
No EOL
2.8 KiB
C++
156 lines
No EOL
2.8 KiB
C++
#ifndef _graph_hpp_
|
||
#define _graph_hpp_
|
||
#include "vector.hpp"
|
||
#include <iostream>
|
||
#include <string>
|
||
// #define gNodeArray(T) binNode<T> *
|
||
|
||
template <class Te>
|
||
class Edge
|
||
{
|
||
public:
|
||
Te data;
|
||
int weight;
|
||
Edge()
|
||
{
|
||
weight = 0;
|
||
}
|
||
Edge(int w)
|
||
{
|
||
weight = w;
|
||
}
|
||
|
||
Edge(Te d, int w)
|
||
{
|
||
data = d;
|
||
weight = w;
|
||
}
|
||
};
|
||
|
||
template <class Tv>
|
||
class Vertex
|
||
{
|
||
public:
|
||
Tv data;
|
||
int inDegree;
|
||
int outDegree;
|
||
Vertex()
|
||
{
|
||
// data = NULL;
|
||
inDegree = 0;
|
||
outDegree = 0;
|
||
}
|
||
Vertex(Tv d)
|
||
{
|
||
data = d;
|
||
inDegree = 0;
|
||
outDegree = 0;
|
||
}
|
||
};
|
||
|
||
template <class Te, class Tv>
|
||
class graphVertex
|
||
{
|
||
private:
|
||
Vector<Vertex<Tv> *> V;
|
||
Vector<Vector<Edge<Te> *>> E;
|
||
int v;
|
||
int e;
|
||
|
||
public:
|
||
graphVertex()
|
||
{
|
||
v = 0;
|
||
e = 0;
|
||
}
|
||
~graphVertex()
|
||
{
|
||
int n = v;
|
||
for (int j = 0; j < n; j++)
|
||
for (int k = 0; k < n; k++)
|
||
delete E[j][k];
|
||
for (int j = 0; j < n; j++)
|
||
delete V[j];
|
||
}
|
||
virtual Tv vertex(int i)
|
||
{
|
||
return V[i]->data;
|
||
}
|
||
virtual int inDegree(int i)
|
||
{
|
||
return V[i]->inDegree;
|
||
}
|
||
virtual int outDegree(int i)
|
||
{
|
||
return V[i]->outDegree;
|
||
}
|
||
virtual int insect(int id, Tv value)
|
||
{
|
||
if (V[id] == NULL)
|
||
{
|
||
Vertex<Tv>* temp= new Vertex<Tv>(value);
|
||
V.put(id, temp);
|
||
// E[id] = new Vector<Edge<Te>>;
|
||
}
|
||
else
|
||
V[id]->data = value;
|
||
v++;
|
||
return id;
|
||
}
|
||
virtual int remove(int id)
|
||
{
|
||
for (int j = 0; j < v; j++)
|
||
{
|
||
if (E[id][j] != NULL)
|
||
{
|
||
delete E[id][j];
|
||
E[id].put(j,NULL);
|
||
V[j]->inDegree--;
|
||
}
|
||
}
|
||
v--;
|
||
Tv temp = vertex(id);
|
||
delete V[id];
|
||
V.put(id, NULL);
|
||
}
|
||
|
||
// id1->id2 进行连接
|
||
// return:
|
||
// -1 顶点不存在
|
||
// -2 边已存在
|
||
// 0 成功
|
||
virtual int link(int id1, int id2, int w)
|
||
{
|
||
if (V[id1] == NULL || V[id2] == NULL)
|
||
return -1;
|
||
if (E[id1][id2] != NULL)
|
||
return -2;
|
||
V[id1]->outDegree++;
|
||
V[id2]->inDegree++;
|
||
Edge<Te>* temp=new Edge<Te>(w);
|
||
E[id1].put(id2, temp);
|
||
return 0;
|
||
}
|
||
// 解除 id1->id2 连接
|
||
// return:
|
||
// -1 顶点不存在
|
||
// -2 边不存在
|
||
// 0 成功
|
||
virtual int unlink(int id1, int id2, int w)
|
||
{
|
||
if (V[id1] == NULL || V[id2] == NULL)
|
||
return -1;
|
||
|
||
if (E[id1][id2] != NULL)
|
||
return -2;
|
||
|
||
V[id1]->outDegree--;
|
||
V[id2]->inDegree--;
|
||
|
||
delete E[id1][id2];
|
||
|
||
return 0;
|
||
}
|
||
};
|
||
|
||
#endif |