首页 > 关于邻接表存储图的问题

关于邻接表存储图的问题

#include "stdio.h"
#include "stdlib.h"
#define MAX_SIZE 20
// 图的邻接矩阵表示法
#define  MaxVertexNum  100
#define  INFINITY  65535
typedef  char  VertexType;      // 顶点类型设为字符型
typedef  int  EdgeType;         // 边的权值设为整型
enum GraphType { DG, UG, DN, UN };// 有向图,无向图,有向网图,无向网图

typedef  struct {
    VertexType  Vertices[ MaxVertexNum ];  // 顶点表
    EdgeType  Edges[ MaxVertexNum ][ MaxVertexNum ];
    int  n, e;              //顶点数n和边数e
    enum GraphType GType;   // 图的类型分4种:UG、DG、UN、DN
} MGraph;
void  CreateMGraph ( MGraph *G )
{
    int  i, j, k, w;
    G-> GType = UN;
                                            //问题出在这里————————————————————
    printf( "输入顶点数:" );
    scanf("%d",&(G->n));//&
    printf("输入边数:");//&
    scanf("%d",&(G->e));//&
    //G->n = 3;//*
    //G->e = 2;//*                            
    printf("输入顶点信息(%d %d):\n",i,G->n);
    for (i = 0; i < G->n;i++){                 
//       printf("%d %d\n",i,G->n);             
      scanf("%c",&(G->Vertices[i]));              
       }                                    //————————————————————————————————
    for ( i = 0; i < G->n; i++ )
       for ( j = 0; j < G->n; j++ )
           G->Edges[i][j] = INFINITY;
    for ( k = 0; k < G->e; k++ ) {
       printf( "输入每条边对应的两个顶点的序号和权值,输入格式为:i, j, w%d:\n",G->e );
       scanf("%d,%d,%d",&i,&j,&w);
       G->Edges[i][j] = w;
       G->Edges[j][i] = w;
    }
}

    int main()
{
    int i = 0;
    MGraph MG;
    CreateMGraph(&MG);
    for(i = 0;i<MG.n;i++){
        for(int j = 0;j < MG.n;j++)
            printf("%5d ",MG.Edges[i][j]);
        printf("\n");
    }
    for(i = 0;i < MG.n;i++)
        printf("%c",MG.Vertices[i]);
    return 0;
}

程序运行时如下

输完顶点信息后还没进入下一步操作就已经输出结果,将for循环中printf("%d %d\n",i,G->n)取消注释后发现第一次循环还没输入信息就进入了第二次循环。

再将带&的行数注释,取消带*的行数发现程序恢复正常,这是什么原因?


好像是连续多个scanf的问题。由于缓冲区的问题,scanf会把上一个回车符当作下一个输入。

看看这篇博文:http://m.blog.chinaunix.net/uid-26404201-id-2991727.html

【热门文章】
【热门文章】