图的邻接表表示
#include <stdio.h>
#include <stdlib.h>
#define MaxVertexNum 100
typedef int Vertex;
typedef int WeightType;
typedef char DataType;
typedef struct ENode
{
Vertex V1, V2;
WeightType Weight;
}*Edge;
typedef struct AdjVNode
{
Vertex AdjV;
WeightType Weight;
struct AdjVNode *Next;
}*PtrToAdjVNode;
typedef struct VNode
{
PtrToAdjVNode FirstEdge;
DataType Data;
}AdjList[MaxVertexNum];
typedef struct GNode
{
int Nv;
int Ne;
AdjList G;
}*LGraph;
LGraph CreateGraph(int VertexNum)
{
Vertex V;
LGraph Graph;
Graph = (LGraph)malloc(sizeof(GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for (V = 0; V < Graph->Nv; V++)
Graph->G[V].FirstEdge = NULL;
return Graph;
}
void InsertEdge(LGraph Graph, Edge E)
{
PtrToAdjVNode NewNode;
NewNode = (PtrToAdjVNode)malloc(sizeof(AdjVNode));
NewNode->AdjV = E->V2;
NewNode->Weight = E->Weight;
NewNode->Next = Graph->G[E->V1].FirstEdge;
Graph->G[E->V1].FirstEdge = NewNode;
NewNode = (PtrToAdjVNode)malloc(sizeof(AdjVNode));
NewNode->AdjV = E->V1;
NewNode->Weight = E->Weight;
NewNode->Next = Graph->G[E->V2].FirstEdge;
Graph->G[E->V2].FirstEdge = NewNode;
}
LGraph BuildGraph()
{
LGraph Graph;
Edge E;
Vertex V;
int Nv,i;
scanf("%d", &Nv);
Graph = CreateGraph(Nv);
scanf("%d", &Graph->Ne);
if (Graph->Ne != 0)
{
E = (Edge)malloc(sizeof(ENode));
for (i = 0; i < Graph->Ne; i++)
{
scanf("%d %d %d", &E->V1, &E->V2, &E->Weight);
InsertEdge(Graph, E);
}
}
for (V = 0; V < Graph->Nv; V++)
scanf("%c", &Graph->G[V].Data);
return Graph;
}
int main()
{
LGraph Graph = BuildGraph();
Vertex V;
PtrToAdjVNode P;
for (V = 0; V < Graph->Nv; V++)
{
for (P = Graph->G[V].FirstEdge; P; P = P->Next)
printf("%d ", P->AdjV);
printf("\n");
}
}
图的邻接矩阵表示
#include <stdio.h>
#include <stdlib.h>
#define MaxVertexNum 100
#define INFINITY 65535
typedef int Vertex;
typedef int WeightType;
typedef char DataType;
typedef struct ENode
{
Vertex V1, V2;
WeightType Weight;
}*Edge;
typedef struct GNode
{
int Nv;
int Ne;
WeightType Weight[MaxVertexNum][MaxVertexNum];
DataType Data[MaxVertexNum];
}*MGraph;
MGraph CreateGraph(int VertexNum)
{
Vertex V, W;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for (V = 0; V < Graph->Nv; V++)
for (W = 0; W < Graph->Nv; W++)
Graph->Weight[V][W] = INFINITY;
return Graph;
}
void InsertEdge(MGraph Graph,Edge E)
{
Graph->Weight[E->V1][E->V2] = E->Weight;
Graph->Weight[E->V2][E->V1] = E->Weight;
}
MGraph BuildGraph()
{
MGraph Graph;
Edge E;
Vertex V;
int Nv, i;
scanf("%d", &Nv);
Graph = CreateGraph(Nv);
scanf("%d", &(Graph->Ne));
if (Graph->Ne != 0)
{
E = (Edge)malloc(sizeof(ENode));
for (i = 0; i < Graph->Ne; i++)
{
scanf("%d %d %d", &E->V1, &E->V2, &E->Weight);
InsertEdge(Graph, E);
}
}
for (V = 0; V < Graph->Nv; V++)
scanf("%c", &Graph->Data[V]);
return Graph;
}
int main()
{
MGraph Graph = BuildGraph();
Vertex V, W;
for (V = 0; V < Graph->Nv; V++)
{
for (W = 0; W < Graph->Nv; W++)
{
printf("%d\t", Graph->Weight[V][W]);
}
printf("\n");
}
return 0;
}