《C语言实现的数据结构》一书深入浅出地讲解了数据结构的基本概念与算法,并通过C语言进行实现和应用示例,适合编程初学者及进阶读者学习参考。
数据结构
```c
/* 校园共有7个结点 */
#include
#include
#define MAXSIZE 50
#define MAXINT 32700 /* 尝试使用32767,但在算法中加法操作可能会导致溢出错误 */
typedef int datatype;
typedef struct {
datatype vexs[MAXSIZE];
int edges[MAXSIZE][MAXSIZE];
int n, e;
} Graph;
void CreateGraph(Graph *graph) {
/* 根据图的结构手工建立邻接矩阵,然后写入程序 */
int i, j;
graph->n = 7;
graph->e = 10;/* 数组下标从1开始使用,以确保顶点表示的一致性 */
for (i = 1; i <= graph->n; ++i) {
graph->vexs[i] = i;
}
/* 初始化边的权重 */
for(i=1;i<=graph->n;i++)
for(j=1;j<=graph->n;j++)
{
if (i == j)
graph->edges[i][j]=0; /* 自环设为零 */
else
graph->edges[i][j] = MAXINT;/* 缺省值设置为无穷大,表示无边连接 */
}
/* 手动设定具体权重值 */
graph->edges[1][2] = 20;
graph->edges[1][3] = 10;
graph->edges[1][4] = 30;
graph->edges[2][7]=9;
graph->edges[3][5]=5;
graph->edges[5][4]=12;
graph->edges[5][7]=15;
graph->edges[6][5]=8;
graph->edges[6][7] = 10;
graph->edges[7][3] = 18;
}
void PrintGraph(Graph * graph) {
int i, j;
printf( );
for (j=1;j<=graph->n;++j)
printf(%6d ,j); /* 确保输出的格式固定 */
printf(\n);
/* 打印邻接矩阵,每行代表一个顶点和所有其他顶点之间的权重关系 */
for(i = 1; i <= graph->n; ++i) {
printf(%d ,i);
for(j=1;j<=graph->n;++j)
printf(%6d ,graph->edges[i][j]);
printf(\n);
}
```
这段代码定义了一个图的数据结构,并通过手工设定的方式创建了校园内7个结点之间的连接关系,最后打印出该图的邻接矩阵。