CS 3343/3341
 Analysis of Algorithms 
  Graph of Capitals, C Version   

Graph construction: 48 mainland US capitals.
// graph.c: set up data structure for graph
// Uses adjacency list representation
#include <stdio.h>
#include <stdlib.h>
#define GRAPHSIZE 48

struct node { // node for graph's vertex
   struct edge* firstedge; // to entire adj. list
   // other vertex info here
};

struct edge { // holds graph's edge info
   int nodenum; // head end of edge
   int edgelen; // data: here it's distance
   struct edge* nextedge; // next edge
   // other edge info here
};

void printgraph(struct node* graph[], int nodes);
struct node* newnode();
struct edge* newedge(int num, struct edge* e, int len);
void insert(struct node* graph[], int num1, int num2, int len);
int edgelength(struct node* graph[], int v1, int v2);
int pathlength(struct node* graph[], int path[], int len);

int main() {
   struct node* graph[GRAPHSIZE];
   int i;
   int num1, num2, len;
   for(i = 0; i < GRAPHSIZE; i++) graph[i] = newnode();

   FILE *infile;
   infile = fopen("capsdist.txt", "r");
   if (infile == NULL) {
      fprintf(stderr, "Can't open %s\n", "source.txt");
      exit(1);
   }
   while (fscanf(infile, "%i%i%i", &num1,&num2,&len) != EOF) {
      // carry out insertions, both directions
      insert(graph, num1, num2, len);
      insert(graph, num2, num1, len);
   }
   printgraph(graph, GRAPHSIZE);
}

struct node* newnode(){
   struct node* nnode = malloc(sizeof(struct node));
   nnode -> firstedge = NULL;
   return nnode;
}

struct edge* newedge(int num, struct edge* e, int len) {
   struct edge* enew = malloc(sizeof(struct edge));
   enew -> nodenum = num;
   enew -> nextedge = e;
   enew -> edgelen = len;
   return enew;
}
  
void insert(struct node* graph[], int num1, int num2, int len){
   // patch the new node in at the start
   graph[num1] -> firstedge = newedge(num2,
      graph[num1] -> firstedge, len);
}


Revision date: 2012-03-21. (Please use ISO 8601, the International Standard Date and Time Notation.)