无向网邻接表
/*无向网的邻接表*/
#include<stdio.h>
#include<stdlib.h>
#define MAX_VERTER_NUM 20
typedef struct ArcNode{ /*表节点*/
int adjvex; /*邻接点*/
struct ArcNode *nextarc; /*指向下一条弧的指针*/
int Weight; /*该弧相关的信息,如权值*/
}ArcNode;
typedef struct VNode{ /*头结点*/
int data; /*定点信息*/
ArcNode * firstarc; /*指向第一个依附该顶点的弧的指针*/
}VNode,AdjList[MAX_VERTER_NUM];
typedef struct{ /*图*/
AdjList vertices; /*顶*/
int vexnum,arcnum; /*图的顶点数和弧数*/
}ALGraph;
int LocateVex(ALGraph * G,int v) /*寻找节点V的位置*/
{
int k,n;
for(k=0;k<G->vexnum;k++){
if(G->vertices[k].data==v){
n=k;break;
}
}
return n;
}
void Print_ALGraph(ALGraph *G) /*打印邻接表*/
{
int i;
ArcNode *a3;
printf("print ALGraph:\n");
for(i=0;i<G->vexnum;i++){
printf(" %d V%d |",i,G->vertices[i].data);
if(G->vertices[i].firstarc!=NULL){
a3=G->vertices[i].firstarc;
while(a3)
{
printf(" -%d-> %d ",a3->Weight,a3->adjvex);
a3=a3->nextarc;
}
}
printf("\n");
}
}
void Insertadj(ALGraph * G,int i,int j,int w) /*插入邻接点的下标*/
{
ArcNode *a1;
a1=(ArcNode *)malloc(sizeof(ArcNode));
a1->adjvex=j;a1->Weight=w;a1->nextarc=NULL;
if(G->vertices[i].firstarc==NULL){
G->vertices[i].firstarc=a1;
}
else{
a1->nextarc=G->vertices[i].firstarc;
G->vertices[i].firstarc=a1;
}
}
void Init_ALGraph(ALGraph * G) /*初始化图并建图*/
{
int v,v1,v2,w,i,j,q,p;
printf("输入(点,边): ");scanf("%d,%d",&G->vexnum,&G->arcnum);
for(v=0;v<G->vexnum;v++){
printf("输入点 V%d:",(v+1));
scanf("%d",&(G->vertices[v].data));
G->vertices[v].firstarc=NULL;
}
for(v=0;v<G->arcnum;v++)
{
printf("输入(点,点,权): ");
scanf("%d,%d,%d",&v1,&v2,&w);
i=LocateVex(G,v1); /*v1的位置*/
j=LocateVex(G,v2); /*v2的位置*/
Insertadj(G,i,j,w);
Insertadj(G,j,i,w);
}
Print_ALGraph(G);
}
int main(int argc,char **argv)
{
ALGraph G;
Init_ALGraph(&G);
return 0;
}