//用邻接表表示图
#include <stdio.h>
#include <stdlib.h>
#define DataType char
#define MaxVertexNum 20
#define Vertex int
#define WeightType int
typedef struct GNode *PtrToGNode;
struct GNode
{
int Nv; //顶点数
int Ne; //边数
AdjList G; //邻接表
};
struct ENode{
Vertex v1, v2;
int weight;
};
typedef struct ENode* Edge;
typedef PtrToGNode LGraph; //以邻接表方式存储的图类型
typedef struct Vnode {
PtrToAdjVNode FirstEdge;
DataType Data; //存顶点的数据
}AdjList[MaxVertexNum];
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode {
Vertex AdjV; //邻接点下标
WeightType Weight; //边的权重
PtrToAdjVNode Next;
};
//初始化一个有VertexNum个顶点但没有边的图
LGraph CreateGraph(int VertexNum)
{
Vertex v;
LGraph Graph;
Graph = (LGraph)malloc(sizeof(struct GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for (v = 0; v < Graph->Nv; v++)
Graph->G[v].FirstEdge = NULL;
return Graph;
}
void InsertEdged(LGraph Graph, Edge E)
{
PtrToAdjVNode NewNode;
NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
NewNode->AdjV = E->v2;
NewNode->Weight = E->weight;
//将v2插入v1的表头
NewNode->Next = Graph->G[E->v1].FirstEdge;
Graph->G[E->v1].FirstEdge = NewNode;
//若是无向图,还要插入边<v2, v1>
//为v1建立新的邻接点
NewNode = (PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
NewNode->AdjV = E->v1;
NewNode->Weight = E->weight;
//将v1插入v2的表头
NewNode->Next = Graph->G[E->v2].FirstEdge;
Graph->G[E->v2].FirstEdge = NewNode;
}