C++写程序确实比C方便的多。
#include<iostream>
#include<queue>
using namespace std;
class ArcNode;
class VexNode
{
public:
//private:
VexNode()
{
vertix=0;
//data=0;
next=NULL;
vTrav=false;
}
VexNode(int ver)
{
this->vertix=ver;
//this->data =data;
this->next =NULL;
vTrav=false;
}
int vertix;
//int data;
ArcNode *next;
bool vTrav;
};
class ArcNode
{
public:
ArcNode()
{
adjvex=0;
data=0;
next=NULL;
aTrav=false;
}
ArcNode(int adj,int data)
{
this->adjvex=adj;
this->data =data;
this->next =NULL;
aTrav=false;
}
//private:
int adjvex;
int data;
ArcNode *next;
bool aTrav;
};
class Graph
{
public:
Graph(int Size) //size=8
{
cout<<“Create the Graph”<<endl;
Vex=new VexNode*[Size];
for(int i=0;i<Size;i++)
{
Vex[i]=new VexNode(i);
}
CreateGraph(Size);
}
~Graph()
{
for(int i=0;i<8;i++)
{
ArcNode *vNode;
vNode=Vex[i]->next;
while(vNode!=NULL)
{
cout<<“ok”<<” “;
Vex[i]->next=vNode->next;
vNode->next=NULL;
delete vNode;
vNode=Vex[i]->next;
}
}
for(int i=0;i<8;i++)
{
//VexNode *vNode=Vex[i];
//delete vNode;
delete Vex[i];
cout<<“ok”<<endl;
}
cout<<“complete”<<endl;
delete [] Vex;
}
bool CreateGraph(int Size)
{
int v1=0;
int v2=0;
bool Enter=true;
int k=0;
while(k<9)
{
cout<<“please Enter v1 and v2″<<endl;
cin>>v1 >>v2;
cout<<v1 <<v2<<endl;
ArcNode *aNode1=new ArcNode(v1,0);
ArcNode *aNode2=new ArcNode(v2,0);
cout<<aNode1->adjvex<<” “<<aNode2->adjvex<<endl;
aNode1->next=Vex[v2]->next;
aNode2->next=Vex[v1]->next;
Vex[v2]->next=aNode1;
Vex[v1]->next=aNode2;
++k;
//if(v1==5&&v2==6)
// break;
}
//print Graph
ArcNode *arcNode;
int i=0;
while(i<Size)
{
cout<<i ;
arcNode=Vex[i]->next;
while(arcNode!=NULL)
{
cout<<arcNode->adjvex ;
arcNode=arcNode->next;
}
++i;
cout<<endl;
}
}
bool BSF()
{
queue<VexNode*>que;
VexNode *node=Vex[0];
que.push(node);
for(int i=0;i<8;i++)
{
VexNode *vNode=que.front();
que.pop();
cout<<vNode->vertix<<” “;
vNode->vTrav=true;
ArcNode *aNode=vNode->next;
while(aNode!=NULL&&(Vex[aNode->adjvex]->vTrav==false))
{
que.push(Vex[aNode->adjvex]);
aNode=aNode->next;
}
}
}
private:
ArcNode *Arc;
VexNode **Vex;
};
int main(int argc,char *argv)
{
Graph graph(8);
graph.BSF();
}
输入数字:
0 1
0 2
1 3
1 4
3 7
4 7
2 5
2 6
5 6