C语言带权无向图的邻接表创建和输出
时间: 2024-03-17 17:44:26 浏览: 34
创建带权无向图的邻接表,可以按照以下步骤实现:
1. 定义结构体存储节点信息和边权值
```c
typedef struct EdgeNode {
int adjvex; // 相邻节点编号
int weight; // 边权值
struct EdgeNode *next; // 指向下一个邻接节点的指针
}EdgeNode;
typedef struct VertexNode {
int vertex; // 当前节点编号
EdgeNode *firstedge; // 指向第一个邻接节点的指针
}VertexNode;
typedef struct Graph {
VertexNode adjlist[MAXSIZE]; // 邻接表
int num_vertexes; // 节点数目
int num_edges; // 边数目
}Graph;
```
2. 初始化邻接表
```c
void initGraph(Graph *G, int n, int m) {
G->num_vertexes = n;
G->num_edges = m;
for (int i = 0; i < n; i++) {
G->adjlist[i].vertex = i;
G->adjlist[i].firstedge = NULL;
}
}
```
3. 添加边
```c
void addEdge(Graph *G, int u, int v, int w) {
EdgeNode *p = (EdgeNode*)malloc(sizeof(EdgeNode));
p->adjvex = v;
p->weight = w;
p->next = G->adjlist[u].firstedge;
G->adjlist[u].firstedge = p;
p = (EdgeNode*)malloc(sizeof(EdgeNode));
p->adjvex = u;
p->weight = w;
p->next = G->adjlist[v].firstedge;
G->adjlist[v].firstedge = p;
}
```
4. 输出邻接表
```c
void printGraph(Graph *G) {
for (int i = 0; i < G->num_vertexes; i++) {
printf("Vertex %d: ", i);
EdgeNode *p = G->adjlist[i].firstedge;
while (p) {
printf("(%d, %d) ", p->adjvex, p->weight);
p = p->next;
}
printf("\n");
}
}
```
完整代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct EdgeNode {
int adjvex;
int weight;
struct EdgeNode *next;
}EdgeNode;
typedef struct VertexNode {
int vertex;
EdgeNode *firstedge;
}VertexNode;
typedef struct Graph {
VertexNode adjlist[MAXSIZE];
int num_vertexes;
int num_edges;
}Graph;
void initGraph(Graph *G, int n, int m) {
G->num_vertexes = n;
G->num_edges = m;
for (int i = 0; i < n; i++) {
G->adjlist[i].vertex = i;
G->adjlist[i].firstedge = NULL;
}
}
void addEdge(Graph *G, int u, int v, int w) {
EdgeNode *p = (EdgeNode*)malloc(sizeof(EdgeNode));
p->adjvex = v;
p->weight = w;
p->next = G->adjlist[u].firstedge;
G->adjlist[u].firstedge = p;
p = (EdgeNode*)malloc(sizeof(EdgeNode));
p->adjvex = u;
p->weight = w;
p->next = G->adjlist[v].firstedge;
G->adjlist[v].firstedge = p;
}
void printGraph(Graph *G) {
for (int i = 0; i < G->num_vertexes; i++) {
printf("Vertex %d: ", i);
EdgeNode *p = G->adjlist[i].firstedge;
while (p) {
printf("(%d, %d) ", p->adjvex, p->weight);
p = p->next;
}
printf("\n");
}
}
int main() {
Graph G;
int n = 5, m = 6;
initGraph(&G, n, m);
addEdge(&G, 0, 1, 1);
addEdge(&G, 0, 2, 2);
addEdge(&G, 1, 2, 3);
addEdge(&G, 1, 3, 4);
addEdge(&G, 2, 3, 5);
addEdge(&G, 3, 4, 6);
printGraph(&G);
return 0;
}
```
阅读全文