c语言从文件读取数据到链表
作者:野牛程序员:2023-11-26 11:53:50C语言阅读 2800
c语言从文件读取数据到链表代码:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 函数声明
void insertNode(struct Node** head, int data);
void displayList(struct Node* head);
void freeList(struct Node* head);
void readDataFromFile(struct Node** head, const char* filename);
// 主函数
int main() {
struct Node* head = NULL; // 初始化链表头指针
// 从文件读取数据到链表
readDataFromFile(&head, "data.txt");
// 显示链表内容
displayList(head);
// 释放链表内存
freeList(head);
return 0;
}
// 将数据插入到链表
void insertNode(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // 分配新节点内存
if (newNode != NULL) {
newNode->data = data;
newNode->next = *head; // 将新节点插入到链表头部
*head = newNode;
} else {
printf("Memory allocation failed.\\n");
exit(EXIT_FAILURE);
}
}
// 显示链表内容
void displayList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\\n");
}
// 释放链表内存
void freeList(struct Node* head) {
struct Node* current = head;
struct Node* nextNode;
while (current != NULL) {
nextNode = current->next;
free(current);
current = nextNode;
}
}
// 从文件读取数据到链表
void readDataFromFile(struct Node** head, const char* filename) {
FILE* file = fopen(filename, "r"); // 打开文件
if (file != NULL) {
int data;
while (fscanf(file, "%d", &data) == 1) {
insertNode(head, data); // 将从文件读取的数据插入链表
}
fclose(file); // 关闭文件
} else {
printf("File not found.\\n");
exit(EXIT_FAILURE);
}
}野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:c++单链表的头插法和尾插法
- 下一篇:c++如何把一个链表加到另一个链表后面
