图的存储结构大赏------数据结构C语言(图)

图的存储结构大赏------数据结构C语言(图)

本次所讲的是常有的四种结构:

  1. 邻接矩阵
  2. 邻接表
  3. 十字链表
  4. 邻接多重表

邻接矩阵

概念

两个数组,一个表示顶点的信息,一个用来表示关联的关系。

  • 如果是无权图,那么1代表有关系,0代表没有关系。
  • 如果是有权图(网)那么用INT_MAX代表没有关系,使用具体的值来代表有关系。

说明

在这里,由于邻接矩阵很好实现,我试着增加难度,使用稀疏矩阵存储无向图。

完整实现:

//注意:所有数组从  0  开始
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char VertexData;
typedef struct Graph
{
    VertexData *data;
    int * matrix;
    int max;
}Graph;
int Locate(int x, int y)
{
    if(x==y)
        return -1;//这种情况不予考虑,因为不考虑自己到自己
    if(y > x)
    {
        int t = y;
        y = x;
        x = t;
    }
    return (x-1)*x/2+y;
}
Graph* Create(int n)
{
    Graph*G = (Graph*)malloc(sizeof(Graph));
    G->max = n;
    G->matrix = (int *)calloc((n-1)*n/2,sizeof(int));
    for(int i = 0; i < (n-1)*n/2; i++)
    {
        G->matrix[i] = 0;
    }
    G->data = (VertexData*)calloc(n,sizeof(VertexData));
    return G;

}
void Fill(Graph *G, int n)
{
    for(int i = 0; i < n; i++)
    {
        char buf[12];
        scanf("%s",buf);
        G->data[i] = buf[0];
    }
}
void AddArc(Graph *G, int n)
{
    for(int i = 0; i < n; i++)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        G->matrix[Locate(a,b)] = 1;
    }
}
void PrintMatrix(Graph *G)
{
    int cnt = 0;
    for(int i = 1; i < G->max; i++)
    {
        for(int j = 0; j < i; j++)
            printf("%d ",G->matrix[cnt++]);
        putchar('\n');
    }
}
int main()
{
    int n;
    scanf("%d",&n);
    Graph *G = Create(n);
    Fill(G,n);
    int m;
    scanf("%d",&m);
    AddArc(G,m);
    PrintMatrix(G);
    return 0;
}

邻接表(链表法)(链式前向星)

话不多说,直接上代码。

由于西工大NOJ已经有相关应用可参考一下博客

基于图的广度优先搜索策略(耿7.11)--------西工大noj.20

基于图的深度优先搜索策略(耿7.10)--------西工大noj

十字链表法

#include<stdio.h>
#include <stdlib.h>
#include <string.h>//我这里的头以及尾巴与书上的不一样。
typedef struct ArcNode
{
    int from, to;
    struct ArcNode * fnext, *tonext;
    int w;
}ArcNode;
typedef struct VertexNode
{
    char info;
    ArcNode *ff, *ft;
}VertexNode;
typedef struct Graph
{
    int num_vertex;
    int num_arc;
    VertexNode *ver;
}Graph;
Graph *Create(int n)
{
    Graph * G = (Graph*)malloc(sizeof(Graph));
    G->num_vertex = n;
    G->num_arc = 0;
    G->ver = (VertexNode*)calloc(n+1, sizeof(VertexNode));
    for(int i = 1; i <= n; i++)
    {
        G->ver[i].ff = NULL;
        G->ver[i].ft = NULL;//在这里可以补加点的信息
    }
    return G;
}
void AddArc(Graph *G,int a, int b, int c)
{
    (G->num_arc)++;
    ArcNode *s = (ArcNode*)malloc(sizeof(ArcNode));
    s->from = a;
    s->to = b;
    s->fnext = G->ver[a].ff;
    G->ver[a].ff = s;
    s->tonext = G->ver[b].ft;
    G->ver[b].ft = s;
    s->w = c;
}
int main()
{
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值