|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include<stdio.h>
- #include<stdlib.h>
- #define MAXV 50
- typedef int infoType;
- typedef int VertexType;
- typedef struct
- {
- int edges[MAXV][MAXV];
- int n,e;
- }Graph;
- typedef struct ANode
- {
- int adjvex;
- struct ANode *nextarc;
- int weight;
- }ArcNode;
- typedef struct Vnode
- {
- ArcNode *firstarc;
- }VNode;
- typedef VNode AdjList[MAXV];
- typedef struct
- {
- AdjList adjlist;
- int n,e;
- }ALGraph;
- void Matrix()
- {
- Graph G;
- printf("请输入顶点总数:\n");
- scanf("%d",&(G.n));
- printf("请输入边数总数:\n");
- scanf("%d",&G.e);
- for(int i=0;i<G.n;i++)
- for(int j=0;j<G.n;j++)
- G.edges[i][j]=0;
- printf("请输入边的起始索引、终止索引和权值:\n");
- for(int i=0;i<G.e;i++)
- {
- int start;
- int end;
- int weight;
- scanf("%d %d %d",&start,&end,&weight);
- G.edges[start][end]=weight;
- }
- printf("输出有向带权图G的邻接矩阵:\n");
- for(int i=0;i<G.n;i++)
- {
- for(int j=0;j<G.n;j++)
- {
- printf("%d\t",G.edges[i][j]);
- }
- printf("\n");
- }
- }
- void MatToList(Graph g,ALGraph *&G) //创建邻接表
- {
- int i,j,n=g.n;
- ArcNode *p;
- G=(ALGraph *)malloc(sizeof(ALGraph));
- 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(g.edges[i][j]!=0)
- {
- p=(ArcNode *)malloc(sizeof(ArcNode));
- p->adjvex=j;
- p->nextarc=G->adjlist[i].firstarc;
- G->adjlist[i].firstarc=p;
- }
- G->n=n;
- G->e=g.e;
- }
- void DispAdj(ALGraph *G)
- {
- int i;
- ArcNode *p;
- printf("\n-------------------------------");
- printf("\n图的邻接表表示:\n");
-
- for(i=0;i<G->n;i++)
- {
-
- printf("\n AdjList[%d]",i);
- p=G->adjlist[i].firstarc;
-
- while(p!=NULL)
- {
- printf("-->%d权值[%d]",p->adjvex,p->weight);
- p=p->nextarc;
- }
-
- }
- printf("\n");
- }
- int main()
- {
- Matrix();
- Graph g;
- ALGraph *G;
- MatToList(g,G);
- DispAdj(G);
- }
复制代码 |
|