无向图 邻接表 建立

#include
#include
#define MAXVEX 100

typedef char VertexType;
typedef int EdgeType;
typedef struct EdgeNode{
	int Adjvex;//存储边对应坐标 
	EdgeType Weight;
	struct EdgeNode* Next;
}EdgeNode;
typedef struct VextexNode{
	VertexType Data;//存储 顶点 
	EdgeNode * FirstEdge;
}VertexNode, AdjList[MAXVEX];

typedef struct{
	AdjList adjList; // adjList 是 struct VertexNode 类型数组 
	int VexNum, EdgeNum;
}GraphAdjList;

//  建立无向连接图(带权重) 
void CreateGraph(GraphAdjList* G)  //传指针  C为值传递  
	{						
		int i, j, k,w;
		EdgeNode *P;
		//printf("输入顶点数和边数:\n");
		scanf("%d%d",&G->VexNum,&G->EdgeNum);
		fflush(stdin);
		//printf("输入顶点信息:\n");
		for(i = 0; i < G->VexNum; i++ ){
			scanf("%d",&G->adjList[i].Data);
			G->adjList[i].FirstEdge = NULL; 
		}
		//printf("输入边(vi, vj)的顶点序号 i, j");
		for(k = 0; k < G->EdgeNum; k++){
			scanf("%d%d%d",&i,&j,&w);
			P = (EdgeNode*)malloc(sizeof(struct EdgeNode));
			P->Adjvex = j;
			P->Weight = w;
			P->Next = G->adjList[i].FirstEdge;
			G->adjList[i].FirstEdge = P;
			
			// 有向图则把这部分 去掉
			P = (EdgeNode*)malloc(sizeof(struct EdgeNode));
			P->Adjvex = i;
			P->Weight = w;
			P->Next = G->adjList[j].FirstEdge;
			G->adjList[j].FirstEdge = P;
		}
	}

void Print(GraphAdjList *G)  
	{
		int i;
		EdgeNode* P;
		for(i = 0; i < G->VexNum; i++ ){
			printf("以v%d为顶点:\n",G->adjList[i].Data);
			P = G->adjList[i].FirstEdge;
			while(P != NULL){
				printf("(v%d,v%d) ->weight = %d\n",G->adjList[i].Data,P->Adjvex,P->Weight);
				P = P->Next;
			}
			printf("\n");
		}
			
	} 
int main()
	{
		GraphAdjList G;
		CreateGraph(&G);
		Print(&G);
		return 0;
	}

你可能感兴趣的:(图论基础)