91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
新和县| 凭祥市| 太原市| 仲巴县| 五大连池市| 汾西县| 柳州市| 汤阴县| 青冈县| 资中县| 长阳| 仁寿县| 盐城市| 渭南市| 肥东县| 嘉黎县| 吴桥县| 漠河县| 淄博市| 长岛县| 岱山县| 会同县| 修文县| 丰都县| 湖南省| 竹溪县| 宜城市| 遂溪县| 贡嘎县| 公主岭市| 通州市| 襄汾县| 习水县| 建宁县| 阿荣旗| 永川市| 长宁区| 孝感市| 娱乐| 勃利县| 绩溪县|