map.c

来自「图的用法」· C语言 代码 · 共 67 行

C
67
字号
#include<stdlib.h>
#include<stdio.h>
struct node               //图的顶点结构
{
	int vertex;           //顶点数据
	struct node *nextnode;
};
typedef struct node *graph;
struct node head[6];
/* --------------------------*/
/*      create the graph       */
/* --------------------------*/
void creategraph(int *node,int num)
{
	graph newnode;           //新顶点指针
	graph ptr;
	int from;                //边的起点
	int to;                  //边的终点
	int i;

	for(i = 0;i < num;i++)    //读取边的循环
	{
		from = node[i * 2];                               //边的起点
		to = node[i * 2 + 1];                            //边的终点
		/* create newnode */
		newnode = (graph )malloc(sizeof(struct node));
		newnode->vertex = to;
		newnode->nextnode = NULL;
		ptr = &(head[from]);
		while(ptr->nextnode != NULL)
			ptr = ptr->nextnode;                          //下一个顶点
		ptr->nextnode = newnode;                          //插入结尾
	}
}
/* --------------------------*/
/*      the main fuction       */
/* --------------------------*/

void main()
{
	graph ptr; 
	int node[12][2] = { {1,2},
		                {1,3},
		                {2,3},
		                {2,4},
		                {3,5},
		                {4,5},  };
	int i;
	for(i = 1;i <= 5;i++ )
	{
		head[i].vertex = i;                 //设置顶点值
		head[i].nextnode = NULL;
	}
    creategraph(node,12);                      //create graph
	printf("tu de ling jie biao lei rong:\n");
	for(i = 1;i <= 5;i++ )
	{
		printf("node%d =>",head[i].vertex);
		ptr = head[i].nextnode;
		while(ptr != NULL)
		{
			printf(" %d ",ptr -> vertex);
			ptr = ptr -> nextnode;
		}
		printf("\n");
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?