-
-
Save marcos-bah/77b6d09a350286b675120052843a87f1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <stdio.h> | |
| #include <stdlib.h> | |
| //representacao dos nós | |
| typedef struct node *link; | |
| struct node { | |
| int w; | |
| link next; | |
| }; | |
| //grafo, sendo v o número de vertices, a o número de arestas e *adj a lista de nós | |
| struct graph { | |
| int V; | |
| int A; | |
| link *adj; | |
| }; | |
| /* Um Graph é um ponteiro para um graph. */ | |
| typedef struct graph *Graph; | |
| //criando novo nó | |
| static link NewNode( int w, link next) { | |
| link a = malloc( sizeof (struct node)); | |
| a->w = w; | |
| a->next = next; | |
| return a; | |
| } | |
| /* REPRESENTAÇÃO POR LISTAS DE ADJACÊNCIA: | |
| A função GRAPHinit() constrói um grafo com vértices 0 1 .. V-1 e nenhum arco. */ | |
| Graph GraphInit( int V) { | |
| Graph G = malloc( sizeof *G); | |
| G->V = V; | |
| G->A = 0; | |
| G->adj = malloc( V * sizeof (link)); | |
| for (int v = 0; v < V; ++v) | |
| G->adj[v] = NULL; | |
| return G; | |
| } | |
| void PrintList(link g) | |
| { | |
| int aux = 0; | |
| printf("["); | |
| while(g!=NULL) | |
| { | |
| printf("%d",g->w); | |
| if (g->next!=NULL) printf(" "); aux++; | |
| g=g->next; | |
| } | |
| printf("] grau = %d\n", aux); | |
| } | |
| //inserindo aresta | |
| void GraphInsertAresta( Graph G, int v, int w) { | |
| for (link a = G->adj[v]; a != NULL; a = a->next) | |
| if (a->w == w) return; | |
| G->adj[v] = NewNode( w, G->adj[v]); | |
| G->A++; | |
| } | |
| void GraphShow( Graph G) { | |
| for (int i = 0; i < G->V; i++) | |
| { | |
| printf("%d: ", i); | |
| PrintList((G->adj)[i]); | |
| } | |
| } | |
| int main() | |
| { | |
| Graph g = GraphInit(6); | |
| GraphInsertAresta(g, 0, 5); | |
| GraphInsertAresta(g, 0, 1); | |
| GraphInsertAresta(g, 1, 5); | |
| GraphInsertAresta(g, 1, 0); | |
| GraphInsertAresta(g, 2, 4); | |
| GraphInsertAresta(g, 3, 1); | |
| GraphInsertAresta(g, 5, 3); | |
| GraphShow(g); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment