亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

c語言如何把鏈表與文件結合

小億
65
2023-12-07 04:39:46
欄目: 編程語言

在C語言中,可以通過文件操作函數將鏈表與文件結合起來。具體步驟如下:

  1. 定義鏈表的結構體
typedef struct Node {
    int data;
    struct Node* next;
} Node;
  1. 實現鏈表的插入、刪除等操作函數
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;
}
  1. 實現將鏈表數據寫入文件的函數
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);
}
  1. 實現從文件中讀取數據到鏈表的函數
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;
}

0
简阳市| 叶城县| 铁力市| 襄汾县| 武川县| 德清县| 济阳县| 手游| 渑池县| 吉隆县| 乐都县| 扶余县| 兴山县| 沙坪坝区| 武威市| 刚察县| 永兴县| 南华县| 安康市| 翁牛特旗| 武平县| 弋阳县| 彰武县| 邯郸县| 静宁县| 恩施市| 太原市| 临朐县| 嫩江县| 色达县| 无为县| 塔城市| 乌拉特前旗| 宜昌市| 松潘县| 开江县| 枣强县| 寻乌县| 雅江县| 台北市| 崇礼县|