【发布时间】:2022-12-19 00:42:23
【问题描述】:
struct ListNode* sortList(struct ListNode* head){
struct ListNode *temp, *change;
int temp_data;
temp = head;
change = head->next; //<<<<<<<<<<<<<<<<<<
while(temp)
{
change = temp->next;
while(change)
{
if (temp->val > change->val)
{
temp_data = temp->val;
temp->val = change->val;
change->val = temp_data;
}
change = change->next;
}
temp = temp->next;
}
return head;
}
leetcode Link
Given the head of a linked list, return the list after sorting it in ascending order.
我试图在 Dev c++ 中编写相同的代码,一切似乎都正常。 在 about 的代码中,我试图将指针更改为指向 head 中的下一个节点,leetcode 给了我一个错误:
Line 13: Char 12: runtime error: member access within null pointer of type 'struct ListNode' [solution.c]
是什么导致了这个错误?它不应该是错误的吧?
【问题讨论】:
-
可能必须处理的一种情况是空列表。在这种情况下,传递给函数的
head指针将为空。如果您描述的错误是由您标记的行触发的,那么这就是原因。 -
在这种情况下,程序是错误的,无论它是否崩溃或报告诊断。此外,看起来您可以简单地完全删除该行,因为该函数从不读取它写入
change的值。后来的change = temp->next在change被读取之前执行。 -
你应该edit并显示minimal reproducible example。那么我们可以给你一个更准确的答案。
标签: c sorting linked-list