zoukankan      html  css  js  c++  java
  • 图的邻接链表实现(c)

    参考:算法:C语言实现 一书

    实现:

    #ifndef GRAPH
    #define GRAPH
    #include<stdio.h>
    #include<stdlib.h>
    struct edge{
    	int v;
    	int w;
    };
    struct node{
    	int v;
    	node* next;
    };
    
    struct graph{
    	int v;
    	int e;
    	node** adj;
    };
    
    node* NEW(int v,node* next)
    {
    	node* x = (node*)malloc(sizeof(node));
    	x->v = v;
    	x->next = next;
    	return x;
    }
    
    graph* graphInit(int v)
    {
    	graph* g = (graph*)malloc(sizeof(graph));
    	g->v = v;
    	g->e = 0;
    	g->adj = (node**)malloc(v*sizeof(node*));
    	for (int v = 0; v < g->v; ++v) g->adj[v] = NULL;
    	return g;
    }
    void graphInsert(graph* g, edge e)
    {
    	int v = e.v, w = e.w;
    	g->adj[v] = NEW(w, g->adj[v]);
    	g->adj[w] = NEW(v, g->adj[w]);
    	++g->e;
    }
    
    void graphShow(graph* g)
    {
    	for (int v = 0; v < g->v; ++v){
    		printf("%d: ", v);
    		node* p = g->adj[v];
    		while (p){
    			printf("%d ", p->v);
    			p = p->next;
    		}
    		printf("
    ");
    	}
    }
    #endif
    

      

    测试:

    #include"graph.h"
    #include<time.h>
    #include<queue>
    using namespace std;
    
    int main()
    {
    	printf("	graph of list test:
    ");
    	graph* g = graphInit(10);
    	edge e[10];
    	for (int i = 0; i < 10; ++i){
    		srand(i);	//使得每次运行产生的数据是一样的,便于分析
    		e[i].v = rand() % 10;
    		e[i].w = rand() % 10;
    		graphInsert(g, e[i]);
    	}
    	graphShow(g);
    	printf("
    ");
    	for (int i = 0; i < 10; ++i)
    		printf("%d %d
    ", e[i].v, e[i].w);
    	printf("
    ");
    }
    

      

  • 相关阅读:
    MS SQL 错误 :17883,严重度: 1,状态: 0
    秒杀架构中高性能可扩展高可用的一点思考
    让IE10等支持classList2.0
    判定元素是否刚插入到DOM树
    accept巨坑
    for in 循环的输出顺序问题
    css斜线
    angular的directive笔记
    avalon最佳实践
    迷你MVVM框架 avalonjs 0.97发布
  • 原文地址:https://www.cnblogs.com/jokoz/p/4755908.html
Copyright © 2011-2022 走看看