C语言邻接表
作者:
qbz666
,
2023-11-29 00:14:23
,
所有人可见
,
阅读 110
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAXN 110
typedef struct edge
{
int adj;//e[]
struct edge *next;//ne[]
int info;//w[]
}edge;
typedef struct node//h[]
{
int data;
edge *first;
}node;
typedef struct ALGraph
{
int ver_num;
int edge_num;
node adjlist[MAXN];//邻接表表头
}ALGraph;
int locate_vex(ALGraph G,int u)
{
for(int i=0;i<G.ver_num;i++)
{
if(u==G.adjlist[i].data)return i;
}
return -1;
}
void create_UDG(ALGraph &G)
{
int n=6,m=7;
G.ver_num=6,G.edge_num=7;
for(int i=0;i<n;i++)
{
G.adjlist[i].data=i;
G.adjlist[i].first=NULL;
}
for(int i=0;i<m;i++)
{
int a,b;scanf("%d%d",&a,&b);
a=locate_vex(G,a);
b=locate_vex(G,b);
edge *p1=(edge*)malloc(sizeof (struct edge));
p1->adj=b;//e[idx]=b;
p1->next=G.adjlist[a].first;//ne[idx]=h[a];
G.adjlist[a].first=p1;//h[a]=idx++;
edge *p2=(edge*)malloc(sizeof (struct edge));
p2->adj=a;//e[idx]=b;
p2->next=G.adjlist[b].first;//ne[idx]=h[a];
G.adjlist[b].first=p2;//h[a]=idx++;
}
}
int main()
{
ALGraph G;
create_UDG(G);
for(int i=0;i<G.ver_num;i++)
{
printf("%d",G.adjlist[i].data);
for(edge *p=G.adjlist[i].first;p;p=p->next)
printf("->%d",p->adj);
printf("\n");
}
}