请阅读整篇文章,因为它包含了非常重要的小细节。
正如C所知道的那样,我们应该处理以下事件 malloc
失败,在这种情况下,我创建了一个名为 destroyList()
的指针,其工作是把指针带到 Node
然后一个一个的销毁。但是我的函数没有被正确的调用... ...
我试着用ptr调用它。merged_out
和 *merged_out
(最后一个是一位社员的建议)但似乎没什么效果。
为什么会这样? 该函数有时会收到 NULL
,空列表或一些随机值。
谁能帮我解决这个问题,让我明白是怎么回事?
typedef struct node_t {
int x;
struct node_t *next;
} *Node;
void destroyList(Node ptr) {
while (ptr) {
Node toDelete = ptr;
ptr = ptr->next;
free(toDelete);
}
}
主函数。
ErrorCode mergeSortedLists(Node list1, Node list2, Node *merged_out) {
if (!list1 || !list2) {
return EMPTY_LIST;
}
if (!isListSorted(list1) || !isListSorted(list2)) {
return UNSORTED_LIST;
}
if (!merged_out) {
return NULL_ARGUMENT;
}
Node ptr = NULL;
int total_len = getListLength(list1) + getListLength(list2);
for (int i = 0; i < total_len; i++) {
int min = getMin(&list1, &list2);
ptr = malloc(sizeof(*ptr));
*merged_out = ptr;
if (!ptr) {
destroyList(*merged_out);
*merged_out = NULL;
return MEMORY_ERROR;
}
ptr->x = min;
ptr->next = NULL;
merged_out = &ptr->next;
}
return SUCCESS;
}
这个函数应该是这样调用的。
Node merged_actual = NULL;
ErrorCode merge_status = mergeSortedLists(list1, list2, &merged_actual);
注意:: getMin()
获取最小值,并将具有该最小值的列表指针推进到下一个节点。
在这些函数之后开始 if
检查。
Node ptr=NULL,last;
/* find out current tail of the list */
if (*merged_out!=NULL){
last=*merged_out;
while (last->next!=NULL){
last=last->next;
}
}
int total_len = getListLength(list1) + getListLength(list2);
for (int i = 0; i < total_len; i++)
{
int min = getMin(&list1, &list2);
ptr = malloc(sizeof(*ptr));
if (!ptr)
{
destroyList(*merged_out);
*merged_out=NULL;
return MEMORY_ERROR;
}
ptr->x = min;
ptr->next = NULL;
/* link ptr onto the list */
if (*merged_out==NULL){
/* if the list is empty, make ptr the head of the list */
*merged_out=ptr;
last=*merged_out;
}
else{
last->next = ptr;
last = ptr;
}
}
请尽量不要复制和粘贴这段代码。它可能正确,也可能不正确,但试着理解它做了什么:每次调用函数时都会迭代,以努力把 last
来指向列表的最后一个元素。因此 merged_out
可以一直指向头部。
@user12986714 我的老账号丢了,被告知不要在意*merged_out的初始值,你能不能更新一下解决方案(删除第一个while循环,不需要2个指针)。