c语言分别用链接表和链接矩阵建一个6个结点的带有权值边的图
时间: 2024-03-14 21:43:11 浏览: 68
使用链表实现:
定义节点和边的结构体:
```c
typedef struct Edge {
int dest; // 目标节点
int weight; // 权值
struct Edge* next; // 下一条边
} Edge;
typedef struct Node {
int id; // 节点编号
Edge* edges; // 与该节点相连的边
} Node;
```
定义一个链表数组来表示图:
```c
Node* graph[6];
```
初始化图:
```c
// 初始化节点
for (int i = 0; i < 6; i++) {
graph[i] = (Node*)malloc(sizeof(Node));
graph[i]->id = i;
graph[i]->edges = NULL;
}
// 添加边
addEdge(graph, 0, 1, 2);
addEdge(graph, 0, 2, 5);
addEdge(graph, 1, 2, 1);
addEdge(graph, 1, 3, 3);
addEdge(graph, 2, 3, 4);
addEdge(graph, 2, 4, 6);
addEdge(graph, 3, 4, 2);
addEdge(graph, 3, 5, 7);
addEdge(graph, 4, 5, 8);
```
其中 `addEdge` 函数用来添加边:
```c
void addEdge(Node* graph[], int src, int dest, int weight) {
// 创建新边节点
Edge* newEdge = (Edge*)malloc(sizeof(Edge));
newEdge->dest = dest;
newEdge->weight = weight;
newEdge->next = NULL;
// 找到源节点
Node* srcNode = graph[src];
// 将新边插入到源节点的边链表中
newEdge->next = srcNode->edges;
srcNode->edges = newEdge;
// 如果是无向图,还需要插入反向边
// addEdge(graph, dest, src, weight);
}
```
使用矩阵实现:
定义一个二维数组来表示图:
```c
int graph[6][6] = {
{0, 2, 5, 0, 0, 0},
{2, 0, 1, 3, 0, 0},
{5, 1, 0, 4, 6, 0},
{0, 3, 4, 0, 2, 7},
{0, 0, 6, 2, 0, 8},
{0, 0, 0, 7, 8, 0}
};
```
其中数组的行和列分别代表节点,数组元素的值代表边的权值。如果两个节点之间没有边,则权值为 0。
阅读全文