首页 > 解决方案 > 为什么我会收到此运行时错误:'Solution::node' (solution.cpp) 类型的空指针内的成员访问

问题描述

我正在解决关于 leetcode 1409. Queries on a Permutation With Key的问题,但是我收到了这个运行时错误,我不知道为什么。我无法调试此错误。

问题陈述:给定1到m之间正整数的数组查询,你必须按照以下规则处理所有查询[i](从i=0到i=queries.length-1):

In the beginning, you have the permutation P=[1,2,3,...,m].
For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i].

返回一个包含给定查询结果的数组。

我的方法:我创建了一个链表来存储从 1 到 m 的整数。然后根据每个查询,我将它传递给一个函数,该函数getpos()返回该查询在列表中的位置,然后根据问题陈述中给出的方向更新它。然后将此返回值添加到结果向量中,该结果向量应该是处理完所有查询后的最终答案。

我添加了注释以更好地理解我的代码

class Solution {
public:
    struct node {
        int data;
        node* next = NULL;
    };
    node* addnode(node* head, int data) {
        if(head == NULL) {
            head = new node;
            head->data = data;
        }
        else {
            node* temp = head;
            while(temp->next != NULL) { temp = temp->next; }
            temp->data = data;
        }
        return head;
    }
    int getpos(node** head, int data) { //To get position of given query
        int count = 0;
        node* temp = *head;
        node* prev;
        while(temp->data != data) {     //runtime error:member access within null pointer of type 'Solution::node' (solution.cpp); SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:32:21
            prev = temp;
            temp = temp->next;
            count++;
        }
        prev->next = temp->next; //searched node deleted
        temp->next = *head;      //add the searched node to beginning of the list
        *head = temp;            //udapate head
        return count;            //we have position stored in count;
    }
    
    vector<int> processQueries(vector<int>& queries, int m) {
        node* head = NULL;
        for(int i=0;i<m;i++) { head = addnode(head,i+1); }
        int n = queries.size();
        vector<int> result;
        for(int i=0;i<n;i++) { result.push_back(getpos(&head,queries[i])); }
        return result;
    }
};

请调试并说明错误原因。我面临许多无法调试的运行时错误。

标签: c++listruntime-errorc++17

解决方案


你的add_node功能有问题。深吸一口气,看看代码。应该在每次调用时add_node分配一个节点。new问问自己,您的版本分配了多少次以及在什么情况下分配了一个新节点?

我相信您可以看到您的代码仅在head等于 NULL 时分配一个新节点,因此它必须被窃听。

顺便说一句,如果你想要一个链表,为什么不使用std::list?你会避免犯下的错误。


推荐阅读