Created
December 16, 2013 14:59
-
-
Save cwndrws/7988352 to your computer and use it in GitHub Desktop.
Some helper functions for building and traversing a graph in c.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
typedef struct Edge Edge; | |
typedef struct Node Node; | |
Edge* EdgewithNodes(Node* src, Node* dest); | |
Node* NodewithInfo(int i); | |
Node* createNodes(int i, int left); | |
void addEdge(Edge* src, Edge* new); | |
void addEdgetoNode(Node* src, Node* dest); | |
// Node type | |
struct Node { | |
Edge* firstEdge; | |
Node* nextNode; | |
int info; | |
}; | |
// Edge type | |
struct Edge { | |
Node* srcNode; | |
Node* destNode; | |
Edge* nextEdge; | |
}; | |
Node* NodewithInfo(int i) { | |
Node* n = malloc(sizeof(Node)); | |
n->info = i; | |
n->firstEdge = NULL; | |
n->nextNode = NULL; | |
return n; | |
} | |
Edge* EdgewithNodes(Node* src, Node* dest) { | |
Edge* e = malloc(sizeof(Edge)); | |
e->srcNode = src; | |
e->destNode = dest; | |
e->nextEdge = NULL; | |
return e; | |
} | |
//Global variable's are not best practice but we're writing this kinda fast. | |
Node Head; | |
Node* createNodes(int i, int left) { | |
Node* newNode = NodewithInfo(i); | |
if (left == 1) { | |
return newNode; | |
} else { | |
newNode->nextNode = createNodes(i + 1, left - 1); | |
return newNode; | |
} | |
} | |
void addEdge(Edge* src, Edge* new) { | |
if (src-> nextEdge == NULL) { | |
src->nextEdge = new; | |
return; | |
} else { | |
return addEdge(src->nextEdge, new); | |
} | |
} | |
void addEdgetoNode(Node* src, Node* dest) { | |
Edge* newEdge = EdgeWithNodes(src, dest); | |
if (src->firstEdge == NULL) { | |
src->firstEdge = newEdge; | |
return; | |
} else { | |
return adddEdge(src->firstEdge, newEdge); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment