看数据结构写代码(36) 图的邻接表表示与实现

图的邻接表表示法,是为每一个顶点建立一个链表,链表里存放着相同弧尾的 弧的信息,这些链表顺序存放在数组中。下面是无向图g2的邻接表 


邻接表 比 邻接矩阵 节省空间,同时 也带来一些操作上的 不便,例如 看 两个顶点是否 相邻,需要 遍历 链表,在 求 无向图顶点的度时,只需 遍历 顶点的链表,而 求 有向图 顶点的度 需要 遍历 整个图 查找 弧头 为这个顶点的 个数。 如果 不想这样做,可以 建立 逆邻接表,即 链表里 存放着 相同 弧头的 弧 的信息。 下一节 要说的 十字链表 类似于这种结构。

下面 上代码:

源代码网盘地址:点击打开链接

// Graph.cpp : 定义控制台应用程序的入口点。
//图的邻接表 表示法

#include "stdafx.h"
#include <cstdlib>
#include <climits>
#define MAX_VERTEX_NUM 20
#define INFINITY INT_MAX
enum E_Graph_Kind  
{  
    DG = 0,//有向图  
    DN,//有向网  
    UDG,//无向图  
    UDN,//无向网  
};  
struct ArcNode//边(弧)
{
	int adjVex;//顶点在数组中的位置
	ArcNode * nextAdj;
	int weight;//权值
};

typedef struct VNode//顶点
{
	ArcNode * head;//头指针
	char vexName;//顶点名称
}AdjList[MAX_VERTEX_NUM];
struct Graph//图
{
	AdjList list;//邻接表
	int arcNum,vexNum;
	E_Graph_Kind kind;
};

//顶点在数组中的位置
int vexLocation(Graph g,char vex){
	for (int i = 0; i < g.vexNum; i++){
		if (g.list[i].vexName == vex){
			return i;
		}
	}
	return -1;
}

ArcNode * getHeadNode(){//获得头节点..
	ArcNode * node = (ArcNode*)malloc(sizeof(ArcNode));
	if (node != NULL){
		node->adjVex = -1;
		node->nextAdj = NULL;
		node->weight = INFINITY;
	}
	return node;
}

ArcNode * getArcNode(Graph g,char vexName){
	ArcNode * node = getHeadNode();
	if (node != NULL){
		int location = vexLocation(g,vexName);
		node->adjVex = location;
	}
	return node;
}

void createDG(Graph * graph);  
void createDN(Graph * graph);  
void createUDG(Graph * graph);  
void createUDN(Graph * graph);  
  
void graphCreate(Graph * graph){  
    E_Graph_Kind kind;  
    printf("请输入要创建的图的类型(有向图:0,有向网:1,无向图:2,无向网:3)\n");  
    scanf("%d",&kind);  
    switch (kind){  
    case DG:  
        createDG(graph);  
        break;  
    case DN:  
        createDN(graph);  
        break;  
    case UDG:  
        createUDG(graph);  
        break;  
  
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值