首页 > 解决方案 > 在函数内部如何检查边缘是否存在,以便在 C 中不会重新插入边缘

问题描述

int addEdge(struct Graph* graph, int src, int dest) {

    struct AdjListNode *newNode = newListNode(dest);
    newNode->next = graph->array[src].head;
    graph->array[src].head = newNode;

    newNode = newListNode(src);
    newNode->next = graph->array[dest].head;
    graph->array[dest].head = newNode;

}

标签: c

解决方案


我就是这样做的!

int addEdge(struct Graph* graph, int src, int dest) {

    if (src == dest) {
        printf("Can't connect the same node");
        return 0;
    }
    node *nodeList2  = graph->array[src].head;
    while (nodeList2  != NULL) {
        if (nodeList2->dest == dest || nodeList2->dest == src) {
            printf(" the edge exists %d και %d", src, dest);
            return 0;
        }
          nodeList2  = nodeList2->next;
        }

        node *newNode = newListNode(dest);
        newNode->next = graph->array[src].head;
        graph->array[src].head = newNode;

        newNode = newListNode(src);
        newNode->next = graph->array[dest].head;
        graph->array[dest].head = newNode;
}

推荐阅读