有向图的创建代码 c语言
时间: 2023-12-04 12:00:12 浏览: 80
创建有向图的代码很简单,我们可以使用邻接矩阵或邻接表来表示有向图。
1. 使用邻接矩阵表示有向图:
```c
#define MAX_VERTEX_NUM 100 // 最大顶点数
typedef struct {
int vertices[MAX_VERTEX_NUM]; // 存储顶点的数组
int edges[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 存储边的二维数组
int vertexCount; // 顶点数量
int edgeCount; // 边数量
} Graph;
void createGraph(Graph *graph) {
int i, j;
printf("请输入顶点的数量:");
scanf("%d", &(graph->vertexCount));
printf("请输入边的数量:");
scanf("%d", &(graph->edgeCount));
for (i = 0; i < graph->vertexCount; i++) {
printf("请输入第 %d 个顶点的值:", i+1);
scanf("%d", &(graph->vertices[i]));
}
for (i = 0; i < graph->vertexCount; i++) {
for (j = 0; j < graph->vertexCount; j++) {
graph->edges[i][j] = 0; // 初始化邻接矩阵
}
}
printf("请依次输入每条边的起点和终点:\n");
for (i = 0; i < graph->edgeCount; i++) {
int startVertex, endVertex;
scanf("%d %d", &startVertex, &endVertex);
graph->edges[startVertex-1][endVertex-1] = 1; // 标记有向边
}
}
```
2. 使用邻接表表示有向图:
```c
#define MAX_VERTEX_NUM 100 // 最大顶点数
typedef struct ArcNode {
int adjvex; // 邻接点的下标
struct ArcNode *next; // 下一个邻接点
} ArcNode;
typedef struct VertexNode {
int data; // 顶点的值
ArcNode *firstArc; // 指向第一个邻接点
} VertexNode;
typedef struct {
VertexNode vertices[MAX_VERTEX_NUM]; // 存储顶点的数组
int vertexCount; // 顶点数量
int edgeCount; // 边数量
} Graph;
void createGraph(Graph *graph) {
int i, j;
printf("请输入顶点的数量:");
scanf("%d", &(graph->vertexCount));
printf("请输入边的数量:");
scanf("%d", &(graph->edgeCount));
for (i = 0; i < graph->vertexCount; i++) {
printf("请输入第 %d 个顶点的值:", i+1);
scanf("%d", &(graph->vertices[i].data));
graph->vertices[i].firstArc = NULL; // 初始化邻接表
}
printf("请依次输入每条边的起点和终点:\n");
for (i = 0; i < graph->edgeCount; i++) {
int startVertex, endVertex;
scanf("%d %d", &startVertex, &endVertex);
ArcNode *arcNode = (ArcNode *)malloc(sizeof(ArcNode));
arcNode->adjvex = endVertex-1;
arcNode->next = graph->vertices[startVertex-1].firstArc;
graph->vertices[startVertex-1].firstArc = arcNode; // 标记有向边
}
}
```
以上代码分别使用邻接矩阵和邻接表来创建有向图。