题目:

试在邻接表存储结构上实现图的基本操作 insert_vertex 和 insert_arc,相关定义如下:

typedef int VertexType;

typedef enum{
    DG, UDG
}GraphType;

typedef struct ArcNode
{
    int adjvex;
    InfoPtr *info;
    struct ArcNode *nextarc;

}ArcNode;

typedef struct VNode
{
    VertexType data;
    ArcNode *firstarc;
}VNode;
typedef struct
{
    VNode vertex[MAX_VERTEX_NUM];
    int vexnum, arcnum;
    GraphType type;
}ListGraph;

int locate_vertex(ListGraph* G, VertexType v); //返回顶点 v 在vertex数组中的下标,如果v不存在,返回-1
bool insert_vertex(ListGraph *G, VertexType v);
bool insert_arc(ListGraph *G, VertexType v, VertexType w);

当成功插入顶点或边时,函数返回true,否则(如顶点或边已存在、插入边时顶点v或w不存在)返回false。

代码:

#include <stdio.h>
#include<stdlib.h>
#include "graph.h" //请勿删除,否则检查不通过

bool insert_vertex(ListGraph* G, VertexType v) {
    // 查找图中是否已存在该顶点
    int v1 = locate_vertex(G, v);
    if (v1 != -1) {
        return false; // 顶点已存在,无法重复插入
    }

    // 增加顶点数,并将新顶点插入到顶点数组的末尾
    G->vexnum++;
    G->vertex[G->vexnum - 1].data = v;
    G->vertex[G->vexnum - 1].firstarc = NULL;

    return true; // 插入成功
}

bool insert_arc(ListGraph* G, VertexType v, VertexType w) {
    // 查找顶点v和w在图中的位置
    int v1 = locate_vertex(G, v);
    if (v1 == -1) {
        return false; // 顶点v不存在,无法插入边
    }
    int v2 = locate_vertex(G, w);
    if (v2 == -1) {
        return false; // 顶点w不存在,无法插入边
    }

    // 检查边(v1, v2)是否已存在 顺便用pre找到vertex[v1]中的最后一个节点方便后续插入
    ArcNode* pre = G->vertex[v1].firstarc;
    ArcNode* p = G->vertex[v1].firstarc;
    while (p != NULL) {
        pre = p;
        if (p->adjvex == v2) {
            return false; // 边已存在,无法重复插入
        }
        p = p->nextarc;
    }

    // 创建新的边节点
    ArcNode* New = (ArcNode*)malloc(sizeof(ArcNode));
    if (New == NULL) {
        return false; // 内存分配失败
    }
    New->adjvex = v2;
    New->nextarc = NULL;

    // 将新节点插入到链表中
    if (pre == NULL) {
        G->vertex[v1].firstarc = New; // 若链表为空,则新节点为头节点
    }
    else {
        pre->nextarc = New; // 否则,在pre节点之后插入新节点
    }

    // 如果图是无向图,还需要插入边(v2, v1)
    if(G->type==UDG){
        ArcNode* pre1 = G->vertex[v2].firstarc;
        ArcNode* p1 = G->vertex[v2].firstarc;
        while (p1 != NULL) {
            pre1 = p1;
            if (p1->adjvex == v1) {
                return false; // 边已存在,无法重复插入
            }
            p1 = p1->nextarc;
        }

        ArcNode* New1 = (ArcNode*)malloc(sizeof(ArcNode));
        if (New1 == NULL) {
            return false; // 内存分配失败
        }
        New1->adjvex = v1;
        New1->nextarc = NULL;

        if (pre1 == NULL) {
            G->vertex[v2].firstarc = New1; // 若链表为空,则新节点为头节点
        }
        else {
            pre1->nextarc = New1; // 否则,在pre1节点之后插入新节点
        }
    }

    G->arcnum++; // 增加边数
    return true; // 插入成功
}
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐