萌新小白,请大家多多指教
//图的邻接多重表存储(仅无向图),结构与有向图的十字链表相似
//顶点存放在数组中,每个顶点结构体都带有一个指向依附于该节点的边的指针
//边中存放该边的两个节点索引及其对应的同依附于该节点的一条边的地址
#include<stdio.h>
#include<stdlib.h>
typedef int* Info;
typedef int VertexType;
struct Edge
{
int mark;//标志位,可用于检测是否遍历过该点或其他用途
int ivex;//边依附的节点索引
int jvex;
struct Edge* ilink;//同依附于i节点的一条边
struct Edge* jlink;
Info information;
};
struct Vertex
{
VertexType data;//顶点信息
Edge* firstedge;//依附于该顶点的一条边(可以是依附于该节点的任意一条边,以输入顺序为准)
};
struct Graph
{
Vertex* vlist;//存放顶点的数组首地址
int vn, en;
};
int Located(Graph& g, int x)
{
for (int i = 0; i < g.vn; i++)
if (g.vlist[i].data == x)
return i;
return g.vn;
}
void CreateGraph(Graph& g)
{
printf("Input vertex number , edge number\n");
scanf("%d%d", &g.vn, &g.en);
g.vlist = (Vertex*)malloc(g.vn * sizeof(Vertex));
if (!g.vlist)
{
printf("malloc error\n");
return;
}
for (int i = 0; i < g.vn; i++)
{
printf("Input vertex\n");
scanf("%d", &g.vlist[i].data);
g.vlist[i].firstedge = NULL;
}
for (int t = 0; t < g.en; t++)
{
int a, b;
printf("Input vertex of the edge\n");
scanf("%d%d", &a, &b);
int i = Located(g, a), j = Located(g, b);
Edge* temp = (Edge*)malloc(sizeof(Edge));
*temp = { 0,i,j,g.vlist[i].firstedge,g.vlist[j].firstedge,NULL };
g.vlist[i].firstedge = g.vlist[j].firstedge = temp;
}
}
void Print(Graph& g)//检测
{
for (int i = 0; i < g.vn; i++)
{
printf("\nVertex: %d ", g.vlist[i].data);
Edge* temp = g.vlist[i].firstedge;
while (temp)
{
printf("\nindex of the edge: %d and %d ", temp->ivex, temp->jvex);
temp = temp->ilink;
}
}
}
int main()
{
Graph g;
CreateGraph(g);
Print(g);
}