在C語言中,可以通過文件操作函數將鏈表與文件結合起來。具體步驟如下:
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* insert(Node* head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
return head;
}
Node* delete(Node* head, int data) {
Node* current = head;
Node* prev = NULL;
while (current != NULL) {
if (current->data == data) {
if (prev == NULL) { // 刪除頭節點
head = current->next;
} else {
prev->next = current->next;
}
free(current);
break;
}
prev = current;
current = current->next;
}
return head;
}
void writeToFile(Node* head, const char* filename) {
FILE* file = fopen(filename, "w");
if (file == NULL) {
printf("Failed to open file!\n");
return;
}
Node* current = head;
while (current != NULL) {
fprintf(file, "%d\n", current->data);
current = current->next;
}
fclose(file);
}
Node* readFromFile(const char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Failed to open file!\n");
return NULL;
}
Node* head = NULL;
int data;
while (fscanf(file, "%d", &data) != EOF) {
head = insert(head, data);
}
fclose(file);
return head;
}
這樣,就可以通過調用這些函數,將鏈表中的數據寫入文件,或者從文件中讀取數據到鏈表中。例如:
int main() {
Node* head = NULL;
// 插入數據到鏈表中
head = insert(head, 1);
head = insert(head, 2);
head = insert(head, 3);
// 將鏈表中的數據寫入文件
writeToFile(head, "data.txt");
// 從文件中讀取數據到鏈表
Node* newHead = readFromFile("data.txt");
// 打印鏈表中的數據
Node* current = newHead;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
// 釋放鏈表內存
while (newHead != NULL) {
Node* temp = newHead;
newHead = newHead->next;
free(temp);
}
return 0;
}