C中的“覆盖”链接列表

时间:2019-02-08 23:10:01

标签: c sorting memory linked-list free

前提: 分配中所需的功能之一是对链接列表进行排序。我完成此操作的方法可能效率很低,但这是我知道如何执行此操作的唯一方法。

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

代码:

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循环运行释放整个列表。

谢谢

1 个答案:

答案 0 :(得分:1)

free(sortedList)呼叫肯定是一个问题。您已经创建了一个完整的链表, 设置pList指向它,然后删除头部。

您很可能希望释放原始列表中的节点,因为您将在新的sortedList中为调用者提供它们的副本。

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