ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* newNode = lists[0];
ListNode* small = NULL;
ListNode* big = NULL;
for(int i = 1; i < lists.size(); i++)
{
small = newNode;
big = newNode -> next;
ListNode* temp = lists[i];
while(temp)
{
if(temp -> val >= small -> val && temp -> val <= big -> val)
{
small -> next = temp;
small = temp;
temp = temp -> next;
small -> next = big;
}
else{
small = big;
big = big -> next;
if(big == NULL){
small -> next = temp;
break;
}
}
}
}
return newNode;
}
我正在练习一个看起来很简单的面试代码。我有一个由一些排序链表组成的数组,我必须将它们全部合并并返回一个排序链表。
但是这段代码给了我一个错误:
第 1037 行:字符 9:运行时错误:引用绑定到“ListNode *”类型的空指针(stl_vector.h)
示例:-
Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] Explanation: The linked-lists are: [ 1->4->5, 1->3->4, 2->6 ] merging them into one sorted list: 1->1->2->3->4->4->5->6
尝试首先使用相同的上下文实现简单的一个,但首先合并两个列表:https://leetcode.com/problems/merge-two-sorted-lists/
您的错误:
例如,为了合并两个列表,我们可以使用比较两个列表的两个当前元素的技术,并通过选择符合我们的标准列表 1 或列表 2 的下一个元素来逐步合并新的合并列表。
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2)
{
if(!list1) return list2;
if(!list2) return list1;
ListNode merged;
ListNode* temp = &merged;
while(list1 && list2)
{
if(list1->val < list2->val)
{
temp->next = list1;
list1 = list1->next ;
}
else
{
temp->next = list2;
list2 = list2->next;
}
temp = temp->next;
std::cout << "Step:" << std::endl;
print(&merged);
print(list1);
print(list2);
}
temp->next = list1 ? list1 : list2;
return merged.next;
}
为了合并更多列表,您应该扩展现有实现,通过列表列表中的所有指针查找最小元素迭代器。并一次又一次地构建下一个节点。列表中的指针可以用作枚举的临时指针,就像在我的例子中我使用了 list1 和 list2。