【发布时间】: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