代码中的print既不是广度优先遍历也不是深度优先遍历,只是为了看出来这个邻接表没创建错,复合要求。
#include<stdio.h>
#include<stdlib.h>
#define MAXV 100
typedef struct ANode{
int adjvex;//该边的邻接点编号
struct ANode* nextarc;//指向下一条边的指针
}ArcNode;//边节点的类型
typedef struct Vnode
{
char info;//顶点的其它信息
ArcNode* firstarc;//指向第一个边结点
}VNode;//邻接表的头节点类型
typedef struct {
VNode adlist[MAXV];//邻接表的头节点数组
int n, e;//图中的顶点数n和边数e
}AdjGraph;//完整的图邻接表类型
void Create(AdjGraph* G)
{
int j, k;ArcNode* s;
scanf("%d %d", &G->n, &G->e);//确定顶点数,边数
for (int i = 0; i < G->n; i++)
{
scanf("%c", &G->adlist[i].info);
G->adlist[i].firstarc = NULL;
}
for (int i = 0; i < G->e; i++)
{
scanf("%d %d", &j, &k);
s = (ArcNode*)malloc(sizeof(ArcNode));
s->adjvex = k;
s->nextarc = G->adlist[j].firstarc;
G->adlist[j].firstarc = s;
}
}
void Create2(AdjGraph* G)
{
int j, k; ArcNode* s,*s2;
scanf("%d %d", &G->n, &G->e);//确定顶点数,边数
for (int i = 0; i < G->n; i++)
{
scanf("%c", &G->adlist[i].info);
G->adlist[i].firstarc = NULL;
}
for (int i = 0; i < G->e; i++)
{
scanf("%d %d", &j, &k);
s2= (ArcNode*)malloc(sizeof(ArcNode));
s = (ArcNode*)malloc(sizeof(ArcNode));
s->adjvex = k;
s->nextarc = G->adlist[j].firstarc;
G->adlist[j].firstarc = s;
s2->adjvex = j;
s2->nextarc = G->adlist[k].firstarc;
G->adlist[k].firstarc = s2;
}
}
void print(AdjGraph* G)
{
ArcNode* p;
for (int i = 0; i < G->n; i++)
{
printf("%c\t", G->adlist[i].info);
p = G->adlist[i].firstarc;
while (p != NULL)
{
printf("%d", p->adjvex);
p = p->nextarc;
}
printf("\n");
}
}
int main()
{
AdjGraph G,G2;
Create (&G);
print(&G);
return 0;
}
create要输入两次边(对于无向图),create2只用输入一次边(create2的写法容易乱序,不建议用,写在这是因为有人问我为什么create不用像邻接表edgs[i][j]=edgs[j][i]=1那样写两个边节点出来),这里用的是头插法
下面是分别使用create和create2的运行结果。