"#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct Node {\n int id;\n char name[50];\n struct Node* next;\n} Node;\n\nNode* createNode(int id, const char* name) {\n Node* newNode = (Node*)malloc(sizeof(Node));\n newNode->id = id;\n strcpy(newNode->name, name);\n newNode->next = NULL;\n return newNode;\n}\n\nvoid insertNode(Node** head, int id, const char* name) {\n Node* newNode = createNode(id, name);\n if (head == NULL) {\n head = newNode;\n } else {\n Node current = head;\n while (current->next != NULL) {\n current = current->next;\n }\n current->next = newNode;\n }\n}\n\nvoid printList(Node head) {\n Node current = head;\n while (current != NULL) {\n printf("ID: %d, Name: %s\n", current->id, current->name);\n current = current->next;\n }\n}\n\nvoid freeList(Node* head) {\n Node* current = head;\n while (current != NULL) {\n Node* temp = current;\n current = current->next;\n free(temp);\n }\n}\n\nint main() {\n Node* head = NULL;\n\n // 假设从数据库中读取了以下数据\n insertNode(&head, 1, "John");\n insertNode(&head, 2, "Alice");\n insertNode(&head, 3, "Bob");\n\n // 打印链表\n printList(head);\n\n // 释放链表内存\n freeList(head);\n\n return 0;\n}\n"这段代码定义了一个名为Node的结构体,包含了一个整型的id和一个字符数组的name,以及指向下一个节点的指针next。\n\ncreateNode函数用于创建新的节点,并初始化节点的idname,并将next指针设为NULL。\n\ninsertNode函数用于将新节点插入链表中。如果链表为空,将新节点设置为头节点;否则,找到最后一个节点,将其next指针指向新节点。\n\nprintList函数用于打印链表中的节点信息。\n\nfreeList函数用于释放链表的内存。\n\n在main函数中,我们假设从数据库中读取了三条数据,并调用insertNode将其插入链表中。然后调用printList函数打印链表的内容,并最后调用freeList函数释放链表的内存。


原文地址: https://www.cveoy.top/t/topic/p4Sy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录