Menu
CoddyTech

添加顶点

Coddy 图:数据结构系列 #9 课程的第 4 课,共 14 课。

顶点是图中的一个点。添加顶点就是在 vertices 映射中登记它的键,并将邻居列表设为空:顶点存在,但还没有任何连接。

如果这个键已经在映射中,就什么也不做。我们不希望仅仅因为有人对同一个顶点调用了两次 addVertex,就清除它已有的邻居。这种幂等行为可以让之后从 addEdge 调用这个方法时更加安全。

来写一下吧。

challenge icon

挑战

简单

为 Graph 类添加一个方法 addVertex。

它接收一个整数 key,并且:

  • 如果 key 不在 vertices 中,就将它添加进去,并将邻居列表设为空。
  • 如果 key 已经在 vertices 中,则不执行任何操作。

亲手试试

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "graph.h"

static int _cmp_int(const void* a, const void* b) {
    int ai = *(const int*)a, bi = *(const int*)b;
    return (ai > bi) - (ai < bi);
}

int main() {
    Graph g;
    Graph_init(&g);
    char line[1024];
    while (fgets(line, sizeof(line), stdin)) {
        line[strcspn(line, "\r\n")] = '\0';
        char* cmd = strtok(line, " \t");
        if (!cmd) continue;
        if (strcmp(cmd, "verticesEmpty") == 0) { printf("%s\n", g.vertexCount == 0 ? "true" : "false"); }
        if (strcmp(cmd, "hasVertex") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%s\n", Graph_indexOf(&g, atoi(arg)) != -1 ? "true" : "false"); }
        if (strcmp(cmd, "addVertex") == 0) { char* arg = strtok(NULL, " \t"); if (arg) Graph_addVertex(&g, atoi(arg)); }
    }
    return 0;
}

图:数据结构系列 #9中的所有课

自己练习: C 在线编译器