【发布时间】:2020-08-25 04:38:08
【问题描述】:
所以,我正在尝试在 C++ 上实现此代码,该代码在链表中的特定位置插入一个元素,但我一直遇到分段错误。我把它缩小到它是主函数中的 l.push(a) 语句,但无法纠正它。
n - 节点数。 然后插入链表。 data - 要插入到列表中的数据。 pos - 要插入数据的位置。
任何有关如何纠正此问题的帮助以及如何避免此类代码中的分段错误的建议将不胜感激:)
//INSERTING ELEMENT AT A SPECIFIC POSITION IN A LINKED LIST - HACKERRANK
#include<iostream>
#include<cstdio>
#include<vector>
#include<limits>
#include<algorithm>
#include<cmath>
using namespace std;
struct Node{
int data;
Node* next;
};
struct Linkedlist{
Node* head;
Linkedlist(){
head= NULL;
}
void push(int data){
Node* temp = new Node;
temp->data = data;
temp->next = NULL;
Node* curr = head;
while(curr->next!=NULL)
curr= curr->next;
curr->next = temp;
}
void pushpos(int data,int pos){
Node *curr = head;
int curr_index = 0;
while((pos-1)!=curr_index){
curr=curr->next;
curr_index++;
}
Node *temp = new Node;
temp->data = data;
temp->next = curr->next;
curr->next = temp;
}
void print(){
Node *curr = head;
while(curr!=NULL){
cout<<curr->data<<endl;
curr = curr->next;
}
}
};
int main(){
int n,i,a,data,pos;
Linkedlist l;
cin>>n;
for(i=0;i<n;i++){
cin>>a;
l.push(a);
}
cout<<"pushed";
cin>>data>>pos;
l.pushpos(data,pos);
l.print();
return 0;
}
【问题讨论】:
-
Node* curr = head; while(curr->next!=NULL)您从未检查过head或curr是否为NULL。在添加第一个节点时考虑空列表的状态。 -
当您遇到分段错误时,您可以在
gdb等调试器中轻松打开核心转储,并且通常会显示导致问题的确切代码行。如果您学会使用调试器,您将花更多时间在计算机上提高工作效率,而花更少的时间提问或胡乱猜测。 -
创建minimal reproducible example 可以让您和我们更轻松地调试问题。此示例的一些提示: 不要要求用户输入;硬编码发生段错误的值
n(最好尽可能小)。同样,将预先确定的值(可能是i)推送到您的列表中。不要因为段错误而永远不会执行的代码(例如对l.pushpos()的调用加上pushpos()的定义)。简化直到 bug 无处可藏。 你的 main 函数最终可能只是int main() { LinkedList l; l.push(0); }。
标签: c++ linked-list segmentation-fault