各位达人帮小弟看看这个程序
#include <vector>
#include <cassert>
#include <iostream>
#include <list>
using namespace std;
struct node
{
int v;
node* next ;
};
class Graph
{
public:
Graph():vec(0),tree(0){};
~Graph();
void InsertNode( int , int ); //插入一个顶点
void DeleteNode( int , int ); //删除一个顶点
void CreateAL(); //创建一个图(顶点表示)
void ShowGraph(); //显示一个图(顶点表示)
void DestroyGraph(); //销毁一个图
void DisplayAdjacencyList(); //显示所有顶点的邻接情况
void CreateAdjacencyList(); //返回一个指针数组 存储每个顶点的邻接顶点
private:
private:
vector< vector< int > > vec; //存储顶点
list<node*> tree; //保存创建的数组
};
Graph::~Graph()
{
if ( tree.empty() ) return ;
list<node*>::iterator it = tree.begin();
while ( it != tree.end() )
{
node *p = (*it)->next;
node *q = NULL;
while( p )
{
q = p;
p = p->next;
delete q;
}
q = NULL;
it++;
}
tree.clear();
cout << "Over!!";
}
void Graph::InsertNode( int x , int y )
{
assert( x < 0 || x > vec.size() || y < 0 || y > vec.size() ); //判断是否越界
vec[x][y] = 1 ;
}
void Graph::DeleteNode( int x , int y )
{
assert( x < 0 || x > vec.size() || y < 0 || y > vec.size() ); //判断是否越界
vec[x][y] = 0 ;
}
void Graph::CreateAL()
{
int x ;
cout << "Please Input 顶点数 Of The Gragh " ;
cin >> x ; //输入顶点数
for ( int i = 0 ; i < x ; i++ )
{
vector<int> temp;
vec.push_back(temp);
for ( int j = 0 ; j < x ; j++ )
vec[i].push_back(0);
} //初始化
cout << "Please Input The Graph (Adjacency Graph) " <<endl; //输入图(顶点表示)
for ( int i = 0 ; i < x ; i++)
for ( int j = 0 ;j < x ; j++)
cin >> vec[i][j] ;
}
void Graph::ShowGraph() //显示图
{
for ( int i = 0 ; i < vec.size() ; i++ )
{
cout << endl;
for ( int j = 0 ; j < vec.size() ; j++ )
cout << vec[i][j] << " ";
}
}
void Graph::DestroyGraph() //销毁图
{
for ( int i = 0 ; i < vec.size() ; i++ )
vec[i].clear();
vec.clear();
}
void Graph::CreateAdjacencyList() //创建一个指针数组 由q返回
{
list<node*>::iterator p = tree.begin(); //数组大小为顶点数
list<node*>::iterator q = p;
for ( int i = 0 ; i < vec.size() ; i++ )
tree.push_back( new node );
for ( ; q != tree.end(); q++ )
(*q)->next = 0;
//记录数组
for ( int i = 0 ; i < vec.size() ; i ++ )
{
for ( int j = 0 ; j < vec.size() ; j++ )
{
if ( vec[i][j] ) //如果存在这个顶点
{
//申请一个新结点
(*p)->next = new node; //接到当前顶点的屁股后面
(*p) = (*p)->next; //向后移一位(记录新的结点)
(*p)->v = j+1; //将所邻接的顶点记录下来
}
(*p)->next = 0;
}
p++;
}
//临时量置空
}
void Graph::DisplayAdjacencyList()
{
list<node*>::iterator p = tree.begin(); //数组大小为顶点数
if ( p != tree.end() )
{
for( int n = 0 ; n < vec.size() ; n++ )
{
cout << endl;
while ((*p)->next )
{
(*p) = (*p)->next;
cout <<"v" << n+1 <<"->v" <<(*p)->v <<" "; //显示
}
p++;
}
}
}
int main()
{
Graph G;
G.CreateAL();
G.ShowGraph();
G.CreateAdjacencyList();
G.DisplayAdjacencyList();
getchar();
getchar();
return 0;
}
输出结果老是出错,在线等