使用虚拟节点添加列表 l1 和列表 l2 的较小节点。最后返回指向虚拟节点旁边的位置以获取实际的合并排序列表,但在返回 dummyNode->next 时获取地址的运行时负载,其中空间不足以容纳 struct ListNode 类型的对象。
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL && l2 != NULL) {
return l2;
}
if (l1 != NULL && l2 == NULL) {
return l1;
}
struct ListNode *dummyNode = NULL;
struct ListNode *head = NULL;
dummyNode = (struct ListNode *)malloc(sizeof(struct ListNode *));
head = dummyNode;
while (l1 != NULL && l2 != NULL) {
if (l1->val <= l2->val) {
head->next = l1;
l1 = l1->next;
head = head->next;
}
else {
head->next = l2;
l2 = l2->next;
head = head->next;
}
}
if (l1 != NULL) {
head->next = l1;
}
if (l2 != NULL) {
head->next = l2;
}
return dummyNode->next;
}
最佳答案
由于传递给 malloc sizeof 指向结构 sizeof(struct ListNode *)
的指针,分配的空间不足。
应该改为为整个结构分配空间 -
dummyNode = (struct ListNode *)malloc(sizeof(struct ListNode));
关于c - 在编写用于合并两个已排序链表的代码时获取地址错误的运行时负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54328192/