图的基本操作(邻接表)

#include<bits/stdc++.h>

#define MAXV 100

#define INF 32767

typedef char InfoType;

typedef struct ANode

{

 int adjvex;

 struct ANode *nextarc;

 int weight;

}ArcNode;

typedef struct Vnode

扫描二维码关注公众号,回复: 15160936 查看本文章

{

 InfoType info;

 ArcNode *firstarc;

}VNode;

typedef struct

{

 Vnode adjlist[MAXV];

 int n,e;

}AdjGraph;

void Create(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)

{

 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("\n");

 }

}

void Destory(AdjGraph *&G)

{

 int i;

 ArcNode *pre,*p;

 for(i=0;i<G->n;i++)

 {

  pre=G->adjlist[i].firstarc;

  if(pre!=NULL)

  {

   p=p->nextarc;

   while(pre!=NULL)

   {

    free(pre);

    pre=p;

    p=p->nextarc;

   }

   free(pre);

  }

 }

 free(G);

}

int main()

{

 AdjGraph *G;

 int A[MAXV][MAXV]={

 {0,8,32767,5,32767},

 {32767,0,3,32767,32767},

 {32767,32767,0,32767,6},

 {32767,32767,9,0,32767},

 {32767,32767,32767,32767,0}};

 int n=5,e=5;

 Create(G,A,n,e);

 DispAdj(G);

}

猜你喜欢

转载自blog.csdn.net/2302_77099705/article/details/130494346