#include<iostream>
#include<string>
using namespace std;
#define MAX_VEX 50
template<class T> //邻接表的链表结构
struct LNode{
int Index;
LNode<T> *next;
LNode():Index(0),next(NULL){}
};
template<class T> //邻接表的数组结构
struct VexNode{
T data;
LNode<T> *first;
VexNode():data(T()),first(NULL){}
};
template<class T>
class Graph
{
public:
Graph()
{
vex=new VexNode<T>[MAX_VEX];
vexcount=0;
edgecount=0;
}
void addVex(T element); //增加顶点
void addEdge(T start,T end); //增加边
void display();
~Graph()
{
delete[] vex;
}
private:
VexNode<T> *vex;
int vexcount;
int edgecount;
};
template<class T>
void Graph<T>::addVex(T element)
{
if((vexcount+1)<=MAX_VEX)
{
VexNode<T> *p=new VexNode<T>;
p->data=element;
p->first=NULL;
vex[vexcount++]=*p;
}
else
{
cout<<"图的顶点已满,不能再添加顶点!"<<endl;
return ;
}
}
template<class T>
void Graph<T>::addEdge(T start,T end)
{
int i,j;
for(i=0;i<vexcount;i++)
{
if(start==vex[i].data)
break;
}
for(j=0;j<vexcount;j++)
{
if(end==vex[j].data)
break;
}
LNode<T> *p=vex[i].first,*q=vex[i].first;
LNode<T> *s=new LNode<T>;
s->Index=j;
s->next=NULL;
if(vex[i].first==NULL)
{
vex[i].first=s;
}
else
{
while(p)
{
q=p;
p=p->next;
}
q->next=s;
}
}
template<class T>
void Graph<T>::display()
{
cout<<"图:"<<endl<<endl;
LNode<T> *p;
for(int i=0;i<vexcount;i++)
{
if(vex[i].first==NULL)
{
cout<<vex[i].data<<endl;
}
else
{
p=vex[i].first;
while(p)
{
cout<<vex[i].data<<"—"<<vex[(p->Index)].data<<endl;
p=p->next;
}
}
}
}
int main()
{
Graph<string> gs;
gs.addVex("v0");
gs.addVex("v1");
gs.addVex("v2");
gs.addVex("v3");
gs.addEdge("v0","v1");
gs.addEdge("v0","v2");
gs.addEdge("v0","v3");
gs.addEdge("v1","v2");
gs.addEdge("v2","v3");
gs.display();
return 0;
}