2018.6.3(图的建立--Adjacency List)

大话数据结构
这里写图片描述

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
const int maxn=110;

struct Edge_Node//边表结点
{
    int data;//邻接点域,存储该顶点对应的下标
    int weight;//存储权值
    Edge_Node *next;//指向下一个邻接点
};
struct Vertex_Node//顶点表结点
{
    int value;//顶点域,存储顶点信息
    Edge_Node *first_edge;//边表头指针,指向边表的第一个结点
};
struct Graph
{
    Vertex_Node adjacency_list[maxn];
    int total_vertex,total_edge;
};

void Create_Graph(Graph *G)
{
    printf("Input the number of the total_vertex and total_edge:\n");
    scanf("%d%d",&G->total_vertex,&G->total_edge);//读入顶点数和边数

    for(int i=0;i<G->total_vertex;i++)
        G->adjacency_list[i].first_edge=NULL;//将边表置为空

    printf("Input the %d set of (vi,vj):\n",G->total_edge);
    for(int i=0;i<G->total_edge;i++)//建立边表Edge_Node
    {
        int vi,vj;
        scanf("%d%d",&vi,&vj);
        //应用了单链表创建中的头插法
        Edge_Node *edge=new Edge_Node;
        edge->data=vj;
        edge->next=G->adjacency_list[vi].first_edge;
        G->adjacency_list[vi].first_edge=edge;
    }
}
void Print(Graph *G)//打印
{
    for(int i=0;i<G->total_vertex;i++)
    {
        printf("%d->",i);
        Edge_Node *edge=G->adjacency_list[i].first_edge;
        while(edge!=NULL)
        {
            printf("%d->",edge->data);
            edge=edge->next;
        }
        printf("NULL\n");
    }
}
int main()
{
    Graph *G=new Graph;

    Create_Graph(G);
    Print(G);

    delete G;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/violet_ljp/article/details/80556460