已知一个带权有向图,其存储结构为邻接表结构 (如图1所示) ,设计一算法,由键盘输入数据,建立邻接表,并将其输出。
用例说明:
第一行输入图的顶点数;
第二行输入顶点信息;
第三行以后按行输入边的信息(位置 1 权值 1 位置 2 权值 2 ……. ,以 -1 结束)。
#include<iostream>
using namespace std;
template <class T>
struct Edge
{
int dest;
T cost;
Edge<T>*next;
};
template <class T,class VerType>
struct Vertex
{
VerType data;
Edge <T>*link;
};
template <class T,class VerType>
class Graph
{
private:
int curNum,e,mark;
public:
int n;
Graph(int sn);
Vertex<T,VerType>*vex;
void InserEdge(const int v1,const int v2,T weight);
template <class U,class V> friend istream & operator >> (istream & in,Graph<U,V> & g);
template <class U,class V> friend ostream & operator << (istream & out,Graph<U,V> & g);
};
template <class T,class VerType>
Graph<T,VerType>::Graph(int sn){ n=sn; vex=new Vertex<T,VerType>[sn];}
template <class T,class VerType>
void Graph<T,VerType>::InserEdge(const int v1,const int v2,T weight)
{
if(v2!=-1)
{
Edge<T>*p=vex[v1].link;
Edge<T>*newNode=new Edge<T>;
vex[v1].link=newNode;
newNode->next=p;
newNode->dest=v2;
newNode->cost=weight;
}
}
template <class T,class VerType>
istream & operator >>(istream & in,Graph<T,VerType> & g)
{
for(int i=0;i<g.n;i++)
{ in>>g.vex[i].data;
g.vex[i].link=NULL;
}
int d,c;
for(int i=0;i<g.n;i++)
{ in>>d;
while(d!=-1)
{
in>>c;
g.InserEdge(i,d,c);
in>>d;
}
}
return in;
}
template <class T,class VerType>
ostream & operator <<(ostream&out,Graph<T,VerType>&g)
{
for(int i=0;i<g.n;i++)
{ Edge<T>*p=g.vex[i].link;
out<<g.vex[i].data<<" ";
while(p!=NULL)
{out<<"("<<i<<","<<p->dest<<")"<<p->cost<<" ";
p=p->next;
}
out<<endl;
}
return out;
}
int main()
{ int a; cin>>a;
Graph<int,char>g(a);
cin>>g;
cout<<g;
return 0;
}