《C语言-数据结构篇章》-图的邻接表建立》

相信读者应该在书中也看到了邻接表表示的示意图了 在使用结构体是要注意命名的可读性和易读性

typedef struct graphy//用来表示网的关系
{   
	int node_position;//结点下表位置
	short int weight;//结点权值
	struct graphy *next;//连接通向的下一个结点
}graphy;
typedef struct message//用来存网的顶点信息
{
  char node;//网的顶点信息
  graphy *head;//网关系的头信息
}message;
typedef struct vex_node//用来存每一个结点信息的开始
{
	message arcs[max];
	int node_number;//结点个数
	int arcs_numbre;//边数
}vex_node;```


#### 创建有向网

```cpp
//创建有向网
vex_node *create_direct_graphy()
{  
   int i=0; 
   vex_node *vexnode;
   vexnode=(vex_node *)malloc(sizeof(vex_node));
   printf("请输入有向网的顶点个数以及边数(x,y)\n");
   scanf("%d,%d",&vexnode->node_number,&vexnode->arcs_numbre);
   getchar();
   for(int i=0;i<vexnode->node_number;i++)
     {
     	//vexnode->arcs[i]=(message *)malloc(sizeof(message));
     	printf("输入第%d个顶点信息\n",i+1);
     	vexnode->arcs[i].node=getchar();
     	getchar();
     	vexnode->arcs[i].head=create_node();
     	  //创建饿函数在下面
     	getchar();
     	printf("下一个顶点信息\n");
     }
     return vexnode;
}

这里要注意的是 head是一个头指针,需要给每一个顶点加上后面的关系

create_node()函数就是每个结点后面的单链表

注意看后每个顶点对应的后面链表
看清有向无向
建立完成后进行遍历

//显示网信息
void display(graphy *gra1)
{  
   graphy *gra=gra1;//必须用新的指针,否则会出错 
   vexdata *p;//必须用新的指针指向,否则会出错
   for(int i=1;i<=gra->node_number;i++)
   {
   	printf("%d:%c:",gra->node[i].position,gra->node[i].node_ch);
   	p=gra->node[i].head;//看上
   	while(p)
   	{
   		printf("(%d,%d)-->>",p->graphy_number,p->weight);
        p=p->next;
   	}
   	printf("\n");
   }
}

总结:着一部分知识主要考察一下对结构体的嵌套结构的运用和理解,一定需要多联系才能够完全掌握好

发布了18 篇原创文章 · 获赞 8 · 访问量 446

猜你喜欢

转载自blog.csdn.net/weixin_45540964/article/details/103207455