C ++中链表代码中的分段错误
Segmentation fault in linked list code in C++
所以,我试图在 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;
}
你在这里犯了几个错误。
1.In 你的 Push API 你没有检查 Null。
void push(int data) {
Node* temp = new Node;
temp->data = data;
temp->next = NULL;
if (head == NULL)
head = temp;
else {
Node* curr = head;
while (curr->next != NULL)
curr = curr->next;
curr->next = temp;
}
}
- 再次在 pushpos 中,您没有检查 NULL 等失败条件,如果 pos 大于链表本身的大小怎么办
所以,我试图在 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;
}
你在这里犯了几个错误。
1.In 你的 Push API 你没有检查 Null。
void push(int data) {
Node* temp = new Node;
temp->data = data;
temp->next = NULL;
if (head == NULL)
head = temp;
else {
Node* curr = head;
while (curr->next != NULL)
curr = curr->next;
curr->next = temp;
}
}
- 再次在 pushpos 中,您没有检查 NULL 等失败条件,如果 pos 大于链表本身的大小怎么办