运行之后输了一组数据就直接segmentaton fault了
#include <stdio.h>
#include <stdlib.h>
#define MaxVerNum 100
typedef int Vertex; //每个vertex的序号
typedef char DataType;
//边
struct ENode{
Vertex V1,V2;
int Weight;
};
typedef struct ENode *Edge;
//每个节点不作表的头节点
typedef struct AdjNode *PtrToAdjNode;
struct AdjNode{
Vertex VAdj;
PtrToAdjNode Next;
int Weight;
};
//每个vertex作为邻接表的头节点时
struct VNode{
PtrToAdjNode First;
DataType data[MaxVerNum][10]; //可选:存储的数据
};
typedef struct VNode List;
//邻接表实现
struct LGragh{
int Nv;
int Ne;
List NodeList[MaxVerNum];
};
typedef struct LGragh *Gragh;
Gragh Initialize(int VerNum);
void InsertEdge(Gragh G,Edge E);
Gragh BuildGragh();
#include "Gragh-link.h"
Gragh Initialize(int VerNum){
Gragh G = (Gragh)malloc(sizeof(struct LGragh));
G->Nv = VerNum;
G->Ne = 0;
for (int i = 0;i < G->Nv-1;i++)
{
G->NodeList[i].First = NULL;
}
return G;
}
void InsertEdge(Gragh G,Edge E)
{
PtrToAdjNode NewNode0 = (PtrToAdjNode)sizeof(struct AdjNode);
NewNode0->Weight = E->Weight;
NewNode0->VAdj = E->V2;
//下面开始插入,插到表头后面
NewNode0->Next = G->NodeList[E->V1].First;
G->NodeList[E->V1].First = NewNode0;
//若为无向图,还要执行以下代码
PtrToAdjNode NewNode1 = (PtrToAdjNode)sizeof(struct AdjNode);
NewNode1->Weight = E->Weight;
NewNode1->VAdj = E->V1;
NewNode1->Next = G->NodeList[E->V2].First;
G->NodeList[E->V2].First = NewNode1;
}
Gragh BuildGragh(){
int Nv,Ne;
Edge E;
do
{
printf("Please enter a number less than 100:");
scanf("%d",&Nv);
} while (Nv >= 100);
Gragh G = Initialize(Nv);
printf("Input the number of edges:");
scanf("%d",&Ne);
G->Ne = Ne;
if (G->Ne != 0)
{
E = (Edge)malloc(sizeof(struct ENode));
printf("please add edges for your gragh.format:Vec1 Vec2 Weight.\n");
for (int i = 0;i < G->Ne;i++)
{
scanf("%d %d %d",&E->V1,&E->V2,&E->Weight);
InsertEdge(G,E);
}
}
/*以下是可选的数据录入*/
//printf("Please add data for each vertex.");
//for (int i = 0;i < G->Nv;i++)
//{
// scanf("%s",G->NodeList[i].data[i]);
//}
return G;
}
int main()
{
Gragh G = BuildGragh();
PtrToAdjNode Neighbour;
int i = 0;
for (;i < G->Nv;i++)
Neighbour = G->NodeList[i].First;
printf("---------%d----------\n",i);
while (Neighbour)
{
printf("%-3d%-3d\n",Neighbour->VAdj,Neighbour->Weight);
Neighbour = Neighbour->Next;
}
system("pause");
return 0;
}