//严蔚敏《数据结构》
//图的存储结构:邻接表
//自学中,加油!!
#include<iostream>
#include<string>
using namespace std;
#define InfoType double
#define VertexType string
const int MaxVertexNum=40;
typedef enum{DG,DN,UDG,UDN} GraphKind;
typedef struct ArcNode
{
int adjvex;//邻接点位置下标
InfoType* info;
struct ArcNode* nextarc;
}ArcNode;//ArcNode 邻接点
typedef struct VNode
{
VertexType data;
ArcNode* firstarc;
}VNode,AdjList[MaxVertexNum];//VNode 顶点 | AdjList 邻接点位置下标(adjvex)的数组
typedef struct
{
AdjList vertices;
int vexnum,arcnum;
GraphKind kind;
}ALGraph;//图
istream& operator>>(istream& is,GraphKind& k)//重载cin>>G.kind(G.kind为枚举量)
{
string kind;
cin>>kind;
int x;
if(kind=="DG")
x=0;
else if(kind=="DN")
x=1;
else if(kind=="UDG")
x=2;
else if(kind=="UDN")
x=3;
switch(x)
{
case 0:k=DG;break;
case 1:k=DN;break;
case 2:k=UDG;break;
case 3:k=UDN;break;
}
return is;
}
int Locate_Vertices(ALGraph G,VertexType v)//返回v在G.vertices数组的位置下标
{
for(int i=0;i!=G.vexnum;i++){
if(G.vertices[i].data==v)
return i;
}
return -1;
}
bool CreatDG(ALGraph& G)//创建有向图的邻接表
{
cout<<"输入有向图的顶点数和弧数:";
cin>>G.vexnum>>G.arcnum;
cout<<"输入"<<G.vexnum<<"个顶点的信息(VertexType为string)\n";
for(int i=0;i!=G.vexnum;i++){
cin>>G.vertices[i].data;
G.vertices[i].firstarc=nullptr;
}
VertexType v1,v2;
int i,j;
ArcNode* p;
for(int k=0;k!=G.arcnum;k++){//输入所有弧的信息
cout<<"输入两个顶点信息:";
cin>>v1>>v2;
i=Locate_Vertices(G,v1);
j=Locate_Vertices(G,v2);
p=new ArcNode;
if(!p)
return false;
p->adjvex=j;
p->info=nullptr;
p->nextarc=G.vertices[i].firstarc;G.vertices[i].firstarc=p;
}
return true;
}
bool CreatDN(ALGraph& G)//创建有向网
{
cout<<"输入有向网的顶点数和弧数:";
cin>>G.vexnum>>G.arcnum;
cout<<"输入"<<G.vexnum<<"个顶点信息\n";
for(int i=0;i!=G.vexnum;i++){
cin>>G.vertices[i].data;
G.vertices[i].firstarc=nullptr;
}
int i,j;
VertexType v1,v2;
ArcNode* p;
InfoType w;
for(int k=0;k!=G.arcnum;k++){//输入所有弧的信息
cout<<"输入两个顶点信息及权值:";
cin>>v1>>v2>>w;
i=Locate_Vertices(G,v1);
j=Locate_Vertices(G,v2);
p=new ArcNode;
if(!p)
return false;
p->adjvex=j;
p->info=new InfoType;//刚开始我的113-114行代码为p->info=&w 十分危险,w会随着该函数的结束而回收
*p->info=w;//而之后的p->info指向被回收的空间 危险!!!
//发现该问题后,将113行代码改为*p->info=w 十分危险,虽分配了p的空间,但p->info并未分配空间
//*p->info就找不到,直接导致运行窗口崩溃
p->nextarc=G.vertices[i].firstarc;G.vertices[i].firstarc=p;
}
return true;
}
bool CreatUDG(ALGraph& G)//创建无向图
{
cout<<"输入无向图的顶点数和边数:";
cin>>G.vexnum>>G.arcnum;
cout<<"输入"<<G.vexnum<<"个顶点信息\n";
for(int i=0;i!
2020-10-8 //严蔚敏《数据结构》 //图的存储结构:邻接表
最新推荐文章于 2022-10-25 19:54:27 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)