运行时错误 - “引用绑定到‘ListNode *’类型的空指针 (stl_vector.h)”

问题描述 投票:0回答:1
 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 

c++ data-structures linked-list singly-linked-list
1个回答
0
投票
  1. https://leetcode.com/problems/merge-k-sorted-lists/任务来自leetcode。
  2. 即使有两个列表,您的实现也不起作用!
  3. 任务标记为“困难”,但恕我直言,如果您没有完成所有简单和中等任务,我不建议您尝试实施困难任务。

尝试首先使用相同的上下文实现简单的一个,但首先合并两个列表:https://leetcode.com/problems/merge-two-sorted-lists/

您的错误:

  1. ListNode* newNode = 列表[0]; // 如果列表为空会怎样?简短回答未定义的行为。此外,您将返回指向未定义内存区域的指针,这是非常肮脏的错误。
  2. 由于很多逻辑问题,实现是错误的。

例如,为了合并两个列表,我们可以使用比较两个列表的两个当前元素的技术,并通过选择符合我们的标准列表 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。

© www.soinside.com 2019 - 2024. All rights reserved.