Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //clang 3.8.0
- #include <stdlib.h>
- #include <stdio.h>
- struct node{
- int vertex;
- struct node *next;
- };
- struct Graph{
- int numVertices;
- struct node **AdjLists;
- };
- typedef struct Graph Graph;
- typedef struct node Node;
- Node* createNode(int);
- Graph* createGraph(int);
- void addEdge(Graph*,int,int);
- void printGraph(Graph*);
- int main(void)
- {
- Graph *g=createGraph(4);
- addEdge(g,0,1);
- addEdge(g,0,2);
- addEdge(g,2,1);
- addEdge(g,3,4);
- printGraph(g);
- return 0;
- }
- Node* createNode(int v){
- Node* newNode=malloc(sizeof(Node));
- newNode->vertex=v;
- newNode->next=NULL;
- return newNode;
- }
- Graph* createGraph(int Vertices){
- Graph *newGraph=malloc(sizeof(Graph));
- newGraph->numVertices=Vertices;
- newGraph->AdjLists=malloc(Vertices*sizeof(Node));
- for(int i=0;i<Vertices;i++ )
- newGraph->AdjLists[i]=NULL;
- return newGraph;
- }
- void addEdge(Graph *p,int src,int des){
- Node *newNode=createNode(des);
- newNode->next=p->AdjLists[src];
- p->AdjLists[src]=newNode;
- newNode=createNode(src);
- newNode->next=p->AdjLists[des];
- p->AdjLists[des]=newNode;
- }
- void printGraph(Graph *p){
- int i;
- for(i=0;i<p->numVertices;i++ ){
- Node *temp=p->AdjLists[i];
- printf("\n Adjacency list of vertex %d\n",i);
- while(temp){
- printf("%d->",temp->vertex);
- temp=temp->next;
- }
- printf("\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement