第六章 6.4 图的存储结构

 6.4.1邻接矩阵

#include<bits/stdc++.h>
using namespace std;
//--------图的邻接矩阵存储表示----------- 
#define MaxInt 32767//表示极大值 
#define MVNum 100//最大顶点数 
#define OK 1
typedef int Status;
typedef char VerTexType;//假设定点的数据类型为字符型 
typedef int ArcType;//假设边的权值类型为整型 
typedef struct {
    VerTexType vexs[MVNum];//顶点表 
    ArcType arcs[MVNum][MVNum];//邻接矩阵 
    int vexnum,arcnum;//图的当前点数和边数 
}AMGraph;

int LocateVex(AMGraph &G,char v)
{
    int i;
    for(i = 0; i < G.vexnum ; i ++)
    {
        if(v == G.vexs[i])
            return i;
    }
}

Status CreatUDN(AMGraph &G)
{
    int i,j,k,w;
    char v1,v2;
    cin>>G.vexnum>>G.arcnum; //输入总顶点数,总边数
    for(i = 0; i < G.vexnum ; i ++)
        cin>>G.vexs[i];//依次输入点的信息
    for(i = 0; i < G.vexnum ; i ++)
        for(j = 0; j < G.vexnum ; j ++)
            G.arcs[i][j] = MaxInt;//初始化邻接矩阵,边的权值均置为极大值MaxInt 
    for(k = 0; k < G.arcnum ; k ++)
    {
        cin>>v1>>v2>>w;//输入一条边依附的顶点及权值 
        i = LocateVex(G,v1);//确定v1在G中的位置 
        j = LocateVex(G,v2);//确定v2在G中的位置 
        G.arcs[i][j] = w;//边<v1,v2>的权值置为w 
        G.arcs[j][i] = G.arcs[i][j];//置<v1,v2>的对称边<v2,v1>的权值为w 
    } 
    return OK;
}

int main()
{
    AMGraph G;
    CreatUDN(G);
    return 0;
}

6.4.2邻接表

#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;
#define MVNum 100
#define OK 1
typedef int OtherInfo;
typedef int Status;
typedef struct ArcNode{//边结点 
    int adjvex;//存储与顶点vi相邻的顶点的位置 
    struct ArcNode *nextarc;//指向下一条边的指针 
    OtherInfo info;
}ArcNode;

typedef struct VexNode{//表头结点 
    int data;//
    ArcNode *firstarc;//指向第一条依附于该顶点的边的指针 
}VexNode,AdjList[MVNum];//AdjList表示邻接表类型 

typedef struct {//邻接表 
    AdjList vertices;
    int vexnum,arcnum;//图的当前顶点和边数 
}ALGraph;

int LocateVex(ALGraph &G,char ch)
{
    for(int i = 0; i < G.vexnum ; i ++)
    {
        if(ch -'0' == G.vertices[i].data )
            return i;
    }
} 
Status CreateUDG(ALGraph &G)
{
    char v1,v2;
    int i,j,k;
    ArcNode *p1,*p2;
    cin>>G.arcnum >>G.vexnum ;//读入总边数,总顶点数 
    for( i = 0; i < G.vexnum  ;i++)
    {
        cin>>G.vertices[i].data ;//输入顶点的值 
        G.vertices [i].firstarc = NULL;//表头结点的指针域为空 
    }
    for( k = 0; k < G.arcnum  ; k ++)//输入各边,构造邻接表 
    {
        cin>>v1>>v2;//输入一条边依附的两个顶点 
        i = LocateVex(G,v1);
        j = LocateVex(G,v2);//确定v1和v2在G中的位置,即 在G中的序号 
        p1 = new ArcNode;//生成一个新的边结点p1 
        p1->adjvex = j;//邻接节点的序号是j 
        p1->nextarc = G.vertices[i].firstarc ;
        G.vertices[i].firstarc = p1;//将新结点p1插入顶点vi的边表头部 
        p2 = new ArcNode;
        p2->adjvex = i;
        p2->nextarc = G.vertices[j].firstarc ;
        G.vertices[j].firstarc = p2;
    }
    return OK;    
}
int main()
{
    ALGraph G;
    CreateUDG(G);
    return 0;
}
原文地址:https://www.cnblogs.com/hellocheng/p/7978870.html