【问题标题】:"Overwriting" Linked Lists in CC中的“覆盖”链接列表
【发布时间】:2019-07-03 05:31:40
【问题描述】:

前提: 分配中所需的功能之一是对链表进行排序。我这样做的方式可能效率很低,但这是我知道的唯一方法。

问题: 如果我有一个信息链表,我将如何(在函数内)“覆盖”传入链表的信息。

代码:

void sortPlaylist(Node **pList) {
    Node * pCur = (*pList);

    // Find size of list
    int size = sizeOfList(*pList);

    // Create a new Node, allocate the memory for a copy of the whole list
    Node * sortedList = NULL;

    // Create an array of the Records in our list
    Record * records;
    records = malloc(size * sizeof(Record));
    for (int i = 0; i < size; i++) {
        records[i] = pCur->record;
        pCur = pCur->pNext;
    }

    // Selection sort the records (it works with arrays, the code is long though)

    // Write the sorted records into a new list
    for (int i = 0; i < size; i++) {
        printf("\nAdding artist to new list %s\n\n", records[i].artist);
        insertFront(&sortedList, records[i]);
        printRecord(sortedList);
    }

    // ERROR HERE I THINK
    // Assign the sorted list to pList
    *pList = sortedList;

    // Free the sortedList
    free(sortedList);
}

错误在于我如何将排序列表分配回我相信的原始 pList。另外我想知道 free(sortedList) 的使用是否正确,它将释放 sortedList 中涉及的所有内存,或者只是指向它的指针,在这种情况下,我想我只是运行一个 for 循环释放整个列表。

谢谢

【问题讨论】:

    标签: c sorting memory linked-list free


    【解决方案1】:

    free(sortedList) 电话绝对是个问题。你已经创建了一个完整的链表, 设置pList指向它,然后删除头部。

    您更有可能想要释放原始列表中的节点,因为您将在新的sortedList 中向调用者提供它们的副本。

    另外,是的,为了不泄漏内存,您需要遍历列表并释放每个节点。 (假设insertFront 正在创建新节点)。

    【讨论】:

    • 另一种选择是同时运行 sortedList 和原始 pList,并将值从一个复制到另一个。然后你可以随时释放 sortedList。更好的选择可能是完全避免复制并重新实现排序算法以处理列表而不是数组。
    • 我想我会选择第二个选项。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 2014-04-30
    • 2014-03-13
    • 1970-01-01
    • 2022-09-23
    • 2016-01-29
    相关资源
    最近更新 更多