已知一个带权有向图,其存储结构为邻接表结构 ,设计一算法,由键盘输入数据,建立邻接表,并将其输出。 用例说明: 第一行输入图的顶点数; 第二行输入顶点信息; 第三行以后,按照顺序,每个顶点对应一行,按行输入该顶点对应边的信息(位置 1 权值 1 位置 2 权值 2 ……. ,以 -1 结束)。 输出格式中,代表链表节点的信息是:(边)权值,参见下面用例。C语言
时间: 2024-02-02 12:03:28 浏览: 75
以下是一个实现该算法的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int val;
int weight;
struct node* next;
};
struct graph {
int n;
struct node** adj;
};
struct node* create_node(int val, int weight) {
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->val = val;
new_node->weight = weight;
new_node->next = NULL;
return new_node;
}
struct graph* create_graph(int n) {
struct graph* new_graph = (struct graph*)malloc(sizeof(struct graph));
new_graph->n = n;
new_graph->adj = (struct node**)malloc(n * sizeof(struct node*));
for (int i = 0; i < n; i++) {
new_graph->adj[i] = NULL;
}
return new_graph;
}
void add_edge(struct graph* g, int u, int v, int w) {
struct node* new_node = create_node(v, w);
new_node->next = g->adj[u];
g->adj[u] = new_node;
}
void print_graph(struct graph* g) {
for (int i = 0; i < g->n; i++) {
printf("Vertex %d: ", i);
struct node* node = g->adj[i];
while (node) {
printf("(%d, %d) -> ", node->val, node->weight);
node = node->next;
}
printf("NULL\n");
}
}
int main() {
int n;
printf("请输入图的顶点数:");
scanf("%d", &n);
struct graph* g = create_graph(n);
printf("请输入顶点信息:");
char vertices[n];
scanf("%s", vertices);
printf("请按行输入每个顶点对应的边信息(以-1结束):\n");
for (int i = 0; i < n; i++) {
printf("请输入顶点%d的边信息:", i);
int v, w, j = 0;
while (scanf("%d%d", &v, &w) == 2 && v != -1) {
add_edge(g, i, v, w);
}
}
print_graph(g);
return 0;
}
```
这个算法的基本思路与Python版本相同。不同之处在于,C语言中需要手动分配内存,使用指针实现链表和图。另外,输入时需要使用`scanf`函数,而循环读取输入直到-1时,需要用到`scanf`的返回值来判断。
阅读全文
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)