zoukankan      html  css  js  c++  java
  • 数据结构与算李春葆系列之图存储

    //实现图的邻接表与邻接矩阵储存并输出 
    #include<stdio.h>
    #include<stdlib.h>
    #define MAXV 100 
    #define INF 32767
    using namespace std;
    typedef struct
    {
    	int no;
    }VertexType;
    typedef struct
    {
    	int edges[MAXV][MAXV];
    	int n,e;
    	VertexType vexs[MAXV];
    }MatGraph;
    typedef struct ANode
    {
    	int adjvex;
    	struct ANode *nextarc;
    	int weight;
    }ArcNode;
    typedef struct Vnode
    {
    	ArcNode *firstarc;
    }VNode;
    
    typedef struct
    {
    	VNode adjlist[MAXV];
    	int n,e;
    }AdjGraph;
    void CreatAdj(AdjGraph *&G,int A[MAXV][MAXV],int n,int e)
    {
    	int i,j;
    	ArcNode *p;
    	G=(AdjGraph *)malloc(sizeof(AdjGraph));
    	for(i=0;i<n;i++)
    	{
    		G->adjlist[i].firstarc=NULL;
    	}
    	for(i=0;i<n;i++)
    	{
    		for(j=n-1;j>=0;j--)
    		{
    			if(A[i][j]!=0&&A[i][j]!=INF)
    			{
    				p=(ArcNode *)malloc(sizeof(ArcNode));
    				p->adjvex=j;
    				p->weight=A[i][j];
    				p->nextarc=G->adjlist[i].firstarc;
    				G->adjlist[i].firstarc=p;
    			}
    		}
    	}
    	G->n=n;
    	G->e=e;
    }
    void DispAdj(AdjGraph *G) //输出邻接表G
    {
        int i;
        ArcNode *p;
        for (i = 0; i < G->n; i++)
        {
            p = G->adjlist[i].firstarc;
            printf("%3d: ", i);
            while (p != NULL)
            {
                printf("%3d[%d]→", p->adjvex, p->weight);
                p = p->nextarc;
            }
            printf("∧
    ");
        }
    }
    void DestroyAdj(AdjGraph *&G)
    {
    	int i;
    	ArcNode *pre,*p;
    	for(i=0;i<G->n;i++)
    	{
    		pre=G->adjlist[i].firstarc;
    		if(pre!=NULL)
    		{
    			p=pre->nextarc;
    			while(p!=NULL)
    			{
    				free(pre);
    				pre=p;p=p->nextarc;
    			}
    			free(pre);
    		}
    	}
    	free(G);
    }
    int main()
    {   int a[6][6];
        int we;
     	int A[MAXV][MAXV] =
        {
            {  0, 5,  INF, 7, INF, INF},
            {INF, 0,  4, INF, INF, INF},
            {  8, INF, 0, INF, INF, 9 },
            {INF, INF, 5, 0, INF, 6   },
            {INF, INF, INF, 5, 0,  INF},
            {  3, INF, INF, INF, 1, 0 }
        };
    	 
    	 AdjGraph *p;
    	 int n=6;
    	 int e=8;
    	 CreatAdj(p,A,n,e);
    	 DispAdj(p);
    	 DestroyAdj(p); 
    	 
    } 
    
  • 相关阅读:
    16解释器模式Interpreter
    15适配器模式Adapter
    14桥接模式Bridge
    13组合模式Composite
    12外观模式Facade
    11代理模式Proxy
    10享元模式Flyweight
    09观察者模式ObServer
    08策略模式Strategy
    07装饰模式Decorator
  • 原文地址:https://www.cnblogs.com/AmosAlbert/p/12832252.html
Copyright © 2011-2022 走看看