Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct AdjListNode
- {
- int dest;
- struct AdjListNode* next;
- }Node_T;
- typedef struct AdjList
- {
- Node_T *head;
- }List_T;
- typedef struct Graph
- {
- int V;
- List_T* array;
- }Graph_T;
- Node_T* newAdjListNode(int dest)
- {
- Node_T* newNode = (Node_T*) malloc(sizeof(Node_T));
- newNode->dest = dest;
- newNode->next = NULL;
- return newNode;
- }
- Graph_T* createGraph(int V)
- {
- Graph_T* graph = (Graph_T*) malloc(sizeof(Graph_T));
- graph->V = V;
- graph->array = (List_T*) malloc(V * sizeof(List_T));
- int i;
- for (i = 0; i < V; ++i)
- graph->array[i].head = NULL;
- return graph;
- }
- void addEdge(Graph_T* graph, int src, int dest)
- {
- Node_T* newNode = newAdjListNode(dest);
- newNode->next = graph->array[src].head;
- graph->array[src].head = newNode;
- newNode = newAdjListNode(src);
- newNode->next = graph->array[dest].head;
- graph->array[dest].head = newNode;
- }
- void printGraph(Graph_T* graph)
- {
- int v;
- for (v = 0; v < graph->V; ++v)
- {
- Node_T* pCrawl = graph->array[v].head;
- printf("\n Adjacency list of vertex %d\n head ", v);
- while (pCrawl)
- {
- printf("-> %d", pCrawl->dest);
- pCrawl = pCrawl->next;
- }
- printf("\n");
- }
- }
- int main()
- {
- int V = 5;
- Graph_T* graph = createGraph(V);
- addEdge(graph, 0, 1);
- addEdge(graph, 0, 4);
- addEdge(graph, 1, 2);
- addEdge(graph, 1, 3);
- addEdge(graph, 1, 4);
- addEdge(graph, 2, 3);
- addEdge(graph, 3, 4);
- // print the adjacency list representation of the above graph
- printGraph(graph);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement