Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct node {
- int vertex;
- struct node* next;
- };
- struct node* createNode(int);
- struct Graph {
- int numVertices;
- struct node** adjLists;
- };
- struct Graph* createGraph(int vertices);
- void addEdge(struct Graph* graph, int src, int dest);
- void printGraph(struct Graph* graph);
- int main() {
- struct Graph* graph = createGraph(6);
- addEdge(graph, 0, 1);
- addEdge(graph, 0, 2);
- printGraph(graph);
- return 0;
- }
- struct node* createNode(int v) {
- struct node* newNode = malloc(sizeof(struct node));
- newNode->vertex = v;
- newNode->next = NULL;
- return newNode;
- }
- struct Graph* createGraph(int vertices) {
- struct Graph* graph = malloc(sizeof(struct Graph));
- graph->numVertices = vertices;
- graph->adjLists = malloc(vertices * sizeof(struct node*));
- int i;
- for (i=0; i<vertices; i++) graph->adjLists[i] = NULL;
- }
- void addEdge(struct Graph* graph, int src, int dest) {
- struct node* newNode = createNode(dst);
- newNode->next = graph->adjLists[src];
- graph->adjLists[src] = newNode;
- newNode = createNode(src);
- newNode->next = graph->adjLists[dest];
- graph->adjLists[dest] = newNode;
- }
- void printGraph(struct Graph* graph) {
- int v;
- for (v=0; v<graph->numVertices; v++) {
- struct node* temp = graph->adjLists[v];
- printf("\nAdjacency list of vertex %d\n", v);
- while (temp) {
- printf("%d -> ", temp->vertex);
- temp = temp->next;
- }
- printf("\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement