数据结构--图

图:一种新的非线性数据结构,在图结构中,数据元素之间的关系是多对多的,即如果任选一个结点作为初始结点,则途中任意一个结点有多个前驱结点和多个后继结点。

两种图
(1)有向图:
n个结点的图中
有n(n-1)条边,任意两个节点之间有方向相反的两条边,则称此图为有向完全图
(2)无向图
n个结点的图中
有n(n-1)/2条边,任意两个结点之间有且只有一条边,则称此图为无向完全图。

自己的实现代码,因为只是为了实现图,很多别的操作没做,但是大抵图的实现是成功的,比较仓促的写的,但是对于图的构造还是成功了

主函数

#include "SeqList.h"
#include <iostream>

using namespace std;

typedef struct RowCol
{
    int row;
    int col;
    int weight;
}RowColWeight;

#define MaxVertices 10
#define MaxWeight 10000
#include "Matrix.h"

void CreateGraph(AdjMGraph* G, char *a, RowColWeight rew[],int num)
{
    int i = 0;
    for (a[i]; a[i] != '\0'; ++i)
    {
        InsertVertices(G,a[i]);
    }


    for (int j = 0; j < num; ++j)
    {
        InsertMartrix(rew[j].row, rew[j].col, G, rew[j].weight);
    }
}

int main()
{
    AdjMGraph graph;
    Initiate(&graph, 5);
    char a[] = "ABCDE";
    RowColWeight rew[] = { {0,1,2},{0,4,20},{1,3,20},{2,1,40},{3,2,50} };

    CreateGraph(&graph, a, rew,5);

    for (int i = 0; i < 5; ++i)
    {
        for (int j = 0; j < 5; ++j)
        {
            cout << graph.edge[i][j] << " ";
        }
        cout << endl;
    }
    for (int i = 0; i < 5; ++i)
    {
        cout << graph.Vertices.list[i].data << " ";
    }
    cout << endl;
    return 0;
}

SeqList.h

#pragma once

typedef struct Adj
{
    int dest;
    Adj* next;
}adj;

typedef struct ListNode
{
    char data;
    int socre;
    adj* next;
}Node;

typedef struct List
{
    Node list[10];
    int size;
}List;

void initList(List* l);
int Insert(char data,List *l);

SeqList.cpp

#include "SeqList.h"

void initList(List* l)
{
    l->size = 0;
}

int Insert(char data, List *l)
{
    if (l->size >= 10)
    {
        return 0;
    }
    else
    {
        l->list[l->size].data = data;
        l->list[l->size].socre = l->size;
        l->size++;
    }
}

Matrix.h

#pragma once
#include "SeqList.h"

typedef struct
{
    List Vertices;//存放结点的顺序表
    int edge[MaxVertices][MaxVertices];//存放边的邻接矩阵
    int numOfEdges;//边的条数
}AdjMGraph;

void Initiate(AdjMGraph *G, int n)
{
    for (int i = 0; i < n; ++i)
    {
        for (int j = 0; j < n; ++j)
        {
            if (i == j)
            {
                G->edge[i][j] = 0;
            }
            else
            {
                G->edge[i][j] = MaxWeight;
            }
        }
    }
    G->numOfEdges = 0;
    initList(&G->Vertices);
}

void InsertVertices(AdjMGraph* G, char data)
{
    Insert(data, &G->Vertices);
}

void InsertMartrix(int row,int col,AdjMGraph* G,int weight)
{
     //不做参数检查了,我就是实现一下图
    G->edge[row][col] = weight;
    G->numOfEdges++;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值