从数据库中读出的数据存到链表 C语言
以下是将从数据库中读出的数据存储到链表的C语言代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int id;
char name[50];
struct Node* next;
} Node;
Node* createNode(int id, const char* name) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->id = id;
strcpy(newNode->name, name);
newNode->next = NULL;
return newNode;
}
void insertNode(Node** head, int id, const char* name) {
Node* newNode = createNode(id, name);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("ID: %d, Name: %s\n", current->id, current->name);
current = current->next;
}
}
void freeList(Node* head) {
Node* current = head;
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
}
int main() {
Node* head = NULL;
// 假设从数据库中读取了以下数据
insertNode(&head, 1, "John");
insertNode(&head, 2, "Alice");
insertNode(&head, 3, "Bob");
// 打印链表
printList(head);
// 释放链表内存
freeList(head);
return 0;
}
这段代码定义了一个名为Node的结构体,包含了一个整型的id和一个字符数组的name,以及指向下一个节点的指针next。
createNode函数用于创建新的节点,并初始化节点的id和name,并将next指针设为NULL。
insertNode函数用于将新节点插入链表中。如果链表为空,将新节点设置为头节点;否则,找到最后一个节点,将其next指针指向新节点。
printList函数用于打印链表中的节点信息。
freeList函数用于释放链表的内存。
在main函数中,我们假设从数据库中读取了三条数据,并调用insertNode将其插入链表中。然后调用printList函数打印链表的内容,并最后调用freeList函数释放链表的内存
原文地址: https://www.cveoy.top/t/topic/imRR 著作权归作者所有。请勿转载和采集!