Code Sharing: C Language Chain Forward Star Template

#include<stdio.h>
#define MAXN 100
#define MAXM 100
int head[MAXN];
int to[MAXM];
int next[MAXM];
int edge_cnt = 0;

// Initialize the graph
void initGraph(int n){
    edge_cnt = 0;
    for(int i=0; i<n; i++){
        head[i] = -1;   // -1 indicates no edge
    }
}

// Add directed edge u->v (head insertion method)
void addEdge(int u, int v){
    to[edge_cnt] = v;  // The to array stores the endpoint of the edge
    next[edge_cnt] = head[u];  // Set the next edge of the new edge as the first edge
    head[u] = edge_cnt;  // Replace the first edge with the new edge, can be understood as inserting at the front of the queue
    edge_cnt ++;  // Increment the edge index
}

// Function to print the graph in order
void printGraph(int n){
    for(int u=0; u<n; u++){
        printf("%d: ", u);
        for(int e=head[u]; e != -1; e=next[e]){
            printf("%d ", to[e]);
        }
        printf("\n");
    }
}

int main(){
    int n = 4;
    initGraph(n);
    addEdge(0, 1);
    addEdge(1, 0);
    addEdge(0, 2);
    addEdge(2, 0);
    addEdge(1, 3);
    addEdge(3, 1);
    addEdge(2, 3);
    addEdge(3, 2);
    printf("Chain Forward Star:\n");
    printGraph(n);
    return 0;
}

Leave a Comment