代码
#include <iostream>
#include <iomanip>
using namespace std;
#define MAXVEX 100
typedef int WeightType ;
typedef int DataType ;
typedef struct GNode * PtrToGNode ;
struct GNode{
int Ne;
int Nv;
WeightType G[ MAXVEX] [ MAXVEX] ;
DataType Data[ MAXVEX] ;
} ;
typedef PtrToGNode MGraph;
typedef int Vertex;
MGraph CreateGraph ( int vertexNum)
{
Vertex V, W;
MGraph MyGraph = new GNode;
MyGraph- > Ne = 0 ;
MyGraph- > Nv = vertexNum;
for ( V= 0 ; V< MyGraph- > Nv; V++ )
{
for ( W= V; W< MyGraph- > Nv; W++ )
{
MyGraph- > G[ V] [ W] = 0 ;
MyGraph- > G[ W] [ V] = 0 ;
}
}
return MyGraph;
}
typedef struct ENode * PtrToENode;
struct ENode{
Vertex v1, v2;
WeightType w;
} ;
typedef PtrToENode Edge;
void InsertEdge ( MGraph Graph, Edge E)
{
Graph- > G[ E- > v1] [ E- > v2] = E- > w;
Graph- > G[ E- > v1] [ E- > v2] = E- > w;
}
MGraph BuildGraph ( )
{
int num_vex;
cout<< "Please input the num of vertex: " ;
cin>> num_vex;
MGraph MyGraph = CreateGraph ( num_vex) ;
cout<< endl<< "Please input the num of edge: " ;
cin>> MyGraph- > Ne;
for ( int i= 0 ; i< MyGraph- > Ne; i++ )
{
Edge edge = new ENode;
cout << endl<< "Please input the edge (eg. vertex1,vertex2,wight ) num" << i<< ": " ;
cin >> edge- > v1 >> edge- > v2 >> edge- > w;
InsertEdge ( MyGraph, edge) ;
cout<< endl;
}
return MyGraph;
}
ostream & operator << ( ostream & cout, MGraph Graph)
{
if ( Graph- > Ne!= 0 )
{
Vertex V, W;
for ( V= 0 ; V< Graph- > Nv; V++ )
{
for ( W= 0 ; W< Graph- > Nv; W++ )
{
cout<< setw ( 5 ) << Graph- > G[ V] [ W] ;
}
cout<< endl;
}
} else {
cout << "This graph has zero edge!" << endl;
}
return cout;
}
int main ( ) {
cout<< BuildGraph ( ) << endl;
return 0 ;
}
输出
Please input the num of vertex: 5
Please input the num of edge: 3
Please input the edge ( eg. vertex1, vertex2, wight ) num0: 0 1 21
Please input the edge ( eg. vertex1, vertex2, wight ) num1: 1 4 32
Please input the edge ( eg. vertex1, vertex2, wight ) num2: 2 3 23
0 21 0 0 0
21 0 0 0 32
0 0 0 23 0
0 0 23 0 0
0 32 0 0 0
Process finished with exit code 0