图的邻接矩阵存储数据结构--自己写数据结构

头文件graph.h


#ifndef _GRAPH_H_
#define _GRAPH_H_

#define  MAX_VER 100
#define  ENDLESS 65535

typedef char VertexType;
typedef int  EdgeType;

typedef struct _Graph
{
    VertexType  ver[MAX_VER];
    EdgeType    edge[MAX_VER][MAX_VER];
    int num_ver,num_edge;    
}Graph,*pGraph;

int locate(pGraph pg,char ch);
void creat_array_graph(pGraph pg);
void print_graph(Graph g);

#endif


实现文件graph.c文件如下

/****************************
文件名:/graph.c 
时间:2014.12.28
作者:XIAO_PING_PING
运行环境:DEV-C++ 4.9.9.2 
内容:图的邻接矩阵存储数据结构
功能:自己写数据结构 
*****************************/
#include <string.h>
#include <stdlib.h>

#include "graph.h"

int locate(pGraph pg,char ch)
{
    int i = 0;
    
    while(ch != pg->ver[i])
    {
        i++;   
    }
    
    return i;    
}

void creat_array_graph(pGraph pg)
{
    int i,j;  
    char cout,cin;
    int num_out,num_in;
    int weight;
    printf("输入顶点数:"); 
    scanf("%d",&pg->num_ver);
    printf("输入边数:"); 
    scanf("%d",&pg->num_edge);
    printf("输入顶点数据:"); 
    for(i = 0;i < pg->num_ver;i++)
    {
        pg->ver[i] = getchar();
        while('\n' == pg->ver[i])
        {
            pg->ver[i] = getchar();           
        }
        printf("点%d:%c\n ",i,pg->ver[i]); 
    }
    
    for(i = 0;i < pg->num_ver;i++)
    {
        for(j = 0;j < pg->num_ver;j++)
        {
            pg->edge[i][j] = ENDLESS;            
        }     
    }
    for(i = 0;i < pg->num_edge;i++)
    { 
        printf("输入要连接的顶点:");  
        cout = getchar();
        while('\n' == cout)
        {
            cout = getchar();           
        }
        cin = getchar();
        while('\n' == cin)
        {
            cin = getchar();           
        }
        printf("权重:"); 
        scanf("%d",&weight);
        num_out = locate(pg,cout);
        num_in = locate(pg,cin);
        pg->edge[num_out][num_in] = weight;
        pg->edge[num_in][num_out] = weight;
    }
} 

void print_graph(Graph g)
{
    int i, j;
    for(i = 0; i < g.num_ver; i++)
    {
        for(j = 0; j < g.num_ver; j++)
        {
            printf("%d      ", g.edge[i][j]);
        }
        printf("\n");
    }
}

测试文件test.c

#include <string.h>
#include <stdlib.h>

#include "graph.h"

int main()
{
    Graph gph;
    
    creat_array_graph(&gph);
    print_graph(gph);
    
    getch();
    return 0;    
}

运行结果如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值