Menu
Coddy logo textTech

Add Vertex

Lesson 4 of 14 in Coddy's Graphs - Data Structures Series #9 course.

A vertex is a single point in the graph. Adding one means registering its key in the vertices map with an empty neighbor list: it exists, but has no connections yet.

If the key is already in the map, do nothing. We do not want to wipe out a vertex's existing neighbors just because someone called addVertex on it twice. That kind of idempotent behavior makes the method safe to call from addEdge later.

Let's write it.

challenge icon

Challenge

Easy

Add a method addVertex to the Graph class.

It takes an integer key and:

  • If key is not in vertices, add it with an empty neighbor list.
  • If key is already in vertices, do nothing.

Try it yourself

#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;
}

All lessons in Graphs - Data Structures Series #9