实验三:无向图邻接表的构造
Posted thusloop
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实验三:无向图邻接表的构造相关的知识,希望对你有一定的参考价值。
基本要求:1. 构造一个无向图的邻接表
屏幕输出
实验拓展:1. 构建有向图的邻接表
2. 判断边是否存在
3. 求顶点的度数
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6;
int n,m;
struct bnode
{
int num;
char data;
struct bnode *next;
};
struct tnode
{
char data;
bnode *firsnode;
} adj[maxn];
void create()
{
printf("输入顶点数和边数:\\n");
cin>>n>>m;
for(int i=1; i<=n; i++)
{
adj[i].firsnode=NULL;
}
}
void join(int x,int y)
{
struct bnode *p,*q;
if(adj[x].firsnode==NULL)
{
p=new bnode;
adj[x].firsnode=p;
p->num=y;
p->next=NULL;
}
else
{
p=adj[x].firsnode;
if(p->num==y)return ;
while(p->next!=NULL)
{
p=p->next;
if(p->num==y)return ;
}
q=new bnode;
p->next=q;
q->num=y;
q->next=NULL;
}
}
void input_wx()
{
for(int i=1; i<=m; i++)
{
int u,v;
cin>>u>>v;
join(u,v);
join(v,u);
}
}
void input_yx()
{
for(int i=1; i<=m; i++)
{
int u,v;
cin>>u>>v;
join(u,v);
}
}
void print()
{
struct bnode *p;
for(int i=1; i<=n; i++)
{
p=adj[i].firsnode;
printf("第%d个结点连的边: ",i);
while(p!=NULL)
{
cout<<p->num<<" ";
p=p->next;
}
cout<<"\\n";
}
}
void test_edge()
{
int u,v;
printf("判断边是否存在,请输入两条边(输入0 0退出!)\\n");
while(cin>>u>>v)
{
if(u==0&&v==0)break;
int flag=0;
struct bnode *p;
p=adj[u].firsnode;
while(p!=NULL)
{
if(p->num==v)
{
flag=1;
break;
}
p=p->next;
}
if(flag)printf("存在!\\n");
else printf("不存在!\\n");
}
}
void test_du()
{
printf("查询节点度数,请输入节点(输入0退出!):\\n");
int x;
struct bnode *p;
while(cin>>x)
{
int sum=0;
if(x==0)break;
p=adj[x].firsnode;
while(p!=NULL)
{
sum++;
p=p->next;
}
printf("节点 %d 的度数为 %d\\n",x,sum);
}
}
int main()
{
create();
input_wx();//输入无向图
//intput_yx();输入有向图
print();
test_edge();//判断边是否存在
test_du();//查询度
}
待完善:增加入度和出度;
以上是关于实验三:无向图邻接表的构造的主要内容,如果未能解决你的问题,请参考以下文章