gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
使用C语言实现下面问题:已知图的邻接矩阵,构建图的邻接表并遍历邻接表。
- User
使用C语言实现下面问题:已知图的邻接矩阵,构建图的邻接表并遍历邻接表。
- Assistant
注:此处提供代码框架,具体实现需根据具体情况进行调整。
#include <stdio.h> #include <stdlib.h> // 定义邻接表节点和邻接表结构体 typedef struct AdjListNode { int dest; // 邻接点的编号 struct AdjListNode *next; // 指向下一个邻接节点的指针 } AdjListNode; typedef struct AdjList { AdjListNode *head; // 指向链表头部的指针 } AdjList; // 定义图的结构体 typedef struct Graph { int V; // 图中节点的数量 AdjList *array; // 指向邻接表数组的指针 } Graph; // 创建邻接节点 AdjListNode *new_adj_node(int dest) { AdjListNode *new_node = (AdjListNode*) malloc(sizeof(AdjListNode)); new_node->dest = dest; new_node->next = NULL; return new_node; } // 创建图 Graph *create_graph(int V, int **adj_mtx) { Graph *graph = (Graph*) malloc(sizeof(Graph)); graph->V = V; graph->array = (AdjList*) malloc(V * sizeof(AdjList)); // 初始化邻接表数组 for (int i = 0; i < V; i++) { graph->array[i].head = NULL; } // 将邻接矩阵转化为邻接表 for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (adj_mtx[i][j] != 0) { AdjListNode *new_node = new_adj_node(j); new_node->next = graph->array[i].head; graph->array[i].head = new_node; } } } return graph; } // 遍历邻接表 void traverse_graph(Graph *graph) { for (int i = 0; i < graph->V; i++) { AdjListNode *curr_node = graph->array[i].head; printf("Node [%d]: ", i); while (curr_node != NULL) { printf("%d ", curr_node->dest); curr_node = curr_node->next; } printf("\n"); } } // 测试程序 int main() { int V = 4; int adj_mtx[4][4] = { {0, 1, 0, 1}, {1, 0, 1, 1}, {0, 1, 0, 1}, {1, 1, 1, 0} }; Graph *graph = create_graph(V, adj_mtx); traverse_graph(graph); return 0; } - User
使用C语言完成下列程序:有一顺序表,元素为{25, 57, 48, 37, 12, 92, 86}。 对表采用冒泡排序(升序),然后采用二分查找表中k=86 的元素,若找到,在其前插入元素73。
- Assistant
注:下面的代码实现使用了一般的数组来模拟顺序表。
#include <stdio.h> // 冒泡排序算法 void bubble_sort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } // 二分查找算法 int binary_search(int arr[], int low, int high, int target) { while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return -1; } // 插入元素到数组中 void insert_element(int arr[], int idx, int val, int n) { for (int i = n - 1; i >= idx; i--) { arr[i+1] = arr[i]; } arr[idx] = val; } int main() { int arr[] = {25, 57, 48, 37, 12, 92, 86}; int n = 7; int k = 86; // 对顺序表进行排序 bubble_sort(arr, n); // 在排好序的顺序表中查找元素 k int idx = binary_search(arr, 0, n-1, k); // 如果找到元素 k,则在其前插入元素 73 if (idx != -1) { insert_element(arr, idx, 73, n); n++; // 数组长度加 1 } else { printf("Element not found.\n"); } // 输出最终的顺序表内容 for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; }