Course contentsShow
← C
Lesson 1042 of 1,21914. Data Structures in CFree lesson

Adding edges in directed graphs

Adding edges in directed graphs

What you'll learn: How to represent a one-way connection between two nodes in a graph using an adjacency list.

In a directed graph (or "digraph"), edges have a specific direction. Think of it like a Twitter follow: if Alice follows Bob, it doesn't mean Bob automatically follows Alice. To represent this in C, we need to update our data structure to show that one node points to another, but not necessarily vice versa.

The Adjacency List Approach

We typically use an Adjacency List to store these connections. Each node in our graph is an index in an array, and each index holds a linked list of all the nodes it points to.

When we add an edge from node A to node B, we only perform one operation: we add B to A's list. We do not touch B's list. This creates the "one-way street" effect.

Implementing the Edge

To add a directed edge, we create a new node and link it to the head of the source node's list. This is much like adding a new element to the front of a standard linked list.

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int vertex;
    struct Node* next;
};

struct Graph {
    int numVertices;
    struct Node** adjLists; // Array of linked lists
};

// Function to add a directed edge from src to dest
void addEdge(struct Graph* graph, int src, int dest) {
    // 1. Create a new node for the destination
    struct Node* newNode = malloc(sizeof(struct Node));
    newNode->vertex = dest;

    // 2. Point new node to the current head of src's list
    newNode->next = graph->adjLists[src];

    // 3. Make the new node the head of src's list
    graph->adjLists[src] = newNode;
    
    // Note: We do NOT add src to dest's list because the graph is directed.
}

How it works in memory

Imagine a graph with three nodes: 0, 1, and 2. If we call addEdge(graph, 0, 1), the array at index 0 will now contain a pointer to a node representing 1. If you look at index 1, its list remains empty.

If this were an undirected graph, you would have to call the logic twice (once for 0 to 1 and once for 1 to 0). In directed graphs, you only do it once, ensuring the relationship remains strictly one-way.

Key takeaway

To add an edge in a directed graph, insert the destination node into the source node's adjacency list only.