帮我用c语言写一段代码,要求实现生成一个链表,存入文件,再从文件中读出该链表
时间: 2024-02-13 09:06:49 浏览: 93
好的,以下是实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// 生成链表
struct Node* createLinkedList(int n) {
struct Node* head = NULL;
struct Node* temp = NULL;
struct Node* p = NULL;
int i, data;
for (i = 0; i < n; i++) {
printf("请输入第 %d 个节点的值: ", i + 1);
scanf("%d", &data);
temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
if (head == NULL) {
head = temp;
} else {
p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
}
}
return head;
}
// 将链表存入文件
void saveLinkedList(struct Node* head) {
FILE* fp = NULL;
struct Node* p = head;
fp = fopen("linkedlist.dat", "wb");
if (fp == NULL) {
printf("文件打开失败\n");
exit(1);
}
while (p != NULL) {
fwrite(&(p->data), sizeof(int), 1, fp);
p = p->next;
}
fclose(fp);
}
// 从文件中读取链表
struct Node* loadLinkedList() {
FILE* fp = NULL;
struct Node* head = NULL;
struct Node* temp = NULL;
int data;
fp = fopen("linkedlist.dat", "rb");
if (fp == NULL) {
printf("文件打开失败\n");
exit(1);
}
while (fread(&data, sizeof(int), 1, fp) != 0) {
temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
if (head == NULL) {
head = temp;
} else {
struct Node* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
}
}
fclose(fp);
return head;
}
// 打印链表
void printLinkedList(struct Node* head) {
struct Node* p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
// 生成链表
head = createLinkedList(5);
// 打印链表
printf("生成的链表为:\n");
printLinkedList(head);
// 将链表存入文件
saveLinkedList(head);
// 从文件中读取链表
head = loadLinkedList();
// 打印链表
printf("从文件中读取的链表为:\n");
printLinkedList(head);
return 0;
}
```
该代码实现了以下功能:
1. 通过用户输入生成一个链表;
2. 将链表存入文件;
3. 从文件中读取链表;
4. 打印链表。
你可以根据自己的需求对该代码进行修改和优化。
阅读全文