【发布时间】:2021-02-11 06:29:01
【问题描述】:
我正在解决一个关于 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(),该函数返回该查询在列表中的位置,然后根据问题陈述中给出的方向更新它。
然后将此返回值添加到结果向量中,该结果向量应该是处理完所有查询后的最终答案。
我添加了 cmets 以便更好地理解我的代码
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;
}
};
请调试并解释错误原因。我面临许多无法调试的运行时错误。
【问题讨论】:
-
你能添加你包含的标题和你的主要功能吗?
-
我在 leetcode 的控制台中编写这段代码,你只能在其中编写返回答案的函数,而输入/输出由 leetcode 自己处理。据我所知,我们可以假设 leetcode 中已经存在所有必要的标头。我已经添加了问题的链接,你可以粘贴我的代码并在那里运行。
-
@AdityaHugay 这里的海报不愿意去第三方网站。更好的操作方式是使用自己的编译器,编写自己的 main 函数,准备好后将代码复制粘贴到 leetcode 中。这将允许您创建自己的测试用例(非常重要)并使用自己的调试器(也非常重要)。这两件事都意味着你可以从使用 leetcode 中学到更多。
标签: c++ list runtime-error c++17