如何在C语言中为链表的每个节点添加描述信息
嘿,我来帮你搞定这个需求!你已经有了链表的基础结构,现在只需要补全Build_list函数,再升级displaylist函数来输出每个节点的详细描述信息就行。下面是完整的实现代码,我还加了详细的注释和说明:
完整代码实现
#include<stdio.h> #include<stdlib.h> //Structure to create Linked list typedef struct iorb { int base_pri; struct iorb *link; char filler[100]; } IORB; IORB * Build_list(int n); void displaylist(IORB * head); int main(){ int n=0; IORB * HEAD = NULL; printf("\nHow many blocks you want to store: "); scanf("%d", &n); HEAD = Build_list(n); displaylist(HEAD); return 0; } // 补全Build_list函数:创建n个节点的链表,每个节点的base_pri设为节点序号(从1开始) IORB * Build_list(int n) { if (n <= 0) { printf("Invalid number of blocks!\n"); return NULL; } IORB *head = NULL; IORB *current = NULL; for (int i = 1; i <= n; i++) { // 分配内存创建新节点 IORB *new_node = (IORB*)malloc(sizeof(IORB)); if (new_node == NULL) { printf("Memory allocation failed for node %d!\n", i); exit(1); } // 设置节点的优先级为当前序号,link初始化为NULL new_node->base_pri = i; new_node->link = NULL; // 填充filler字段(可选,这里用序号标识内容) snprintf(new_node->filler, sizeof(new_node->filler), "Node %d filler content", i); // 将新节点链接到链表中 if (head == NULL) { head = new_node; current = new_node; } else { current->link = new_node; current = new_node; } } return head; } // 修改displaylist函数:输出每个节点的详细描述信息 void displaylist(IORB * head) { if (head == NULL) { printf("Linked list is empty!\n"); return; } IORB *current = head; int node_count = 1; printf("\n--- Linked List Node Details ---\n"); while (current != NULL) { printf("* Node %d:\n", node_count); printf(" - base_pri value: %d\n", current->base_pri); printf(" - Current node address: %p\n", (void*)current); printf(" - Next node address: %p\n", (void*)current->link); printf(" - Filler content: %s\n", current->filler); printf("-------------------------------\n"); current = current->link; node_count++; } }
关键修改说明
Build_list函数补全:
- 先判断输入的节点数
n是否合法(必须大于0),避免无效输入导致的问题。 - 循环创建每个节点,给
base_pri赋值为节点的序号(从1开始,方便和输出的节点序号对应),同时给filler字段填充了标识内容,你可以根据实际需求修改填充的内容。 - 增加了内存分配失败的判断,一旦分配失败会打印提示并退出,避免程序崩溃。
- 先判断输入的节点数
displaylist函数增强:
- 遍历链表时,给每个节点加上了序号标识,输出的信息非常直观:
- 节点的序号(第几个节点)
base_pri字段的具体数值- 当前节点的内存地址(方便调试时查看节点的内存位置)
- 下一个节点的内存地址(能清晰看到链表的链接关系)
filler字段的内容(如果有填充的话)
- 增加了空链表的判断,当链表为空时会打印提示信息,不会出现异常。
- 遍历链表时,给每个节点加上了序号标识,输出的信息非常直观:
运行这段代码后,你输入想要创建的节点数量,就能看到每个节点的详细描述信息了。
内容的提问来源于stack exchange,提问作者Moofi
相关产品推荐
相关产品推荐

