So, i'm trying to implement this code on C++ which inserts an element at a specific position in a linked list and I keep getting a segmentation fault. I've narrowed it down to it being the l.push(a) statement in the main function but can't rectify it.
n - number of nodes. then the linked list is inserted. data - the data to be inserted in the list. pos - the position in which the data is to be inserted.
Any help on how to rectify this and advice on how to avoid segmentation faults in such code would be much appreciated :)
//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)You never checked ifheadorcurrwereNULL. Think about the state of an empty list when you're adding the first node.gdband often reveal the exact line of code that caused the problem. If you learn to use a debugger, you will spend more time being productive at the computer and less time asking questions or making wild guesses.n(preferably as small as possible) for which the segfault occurs. Similarly, push pre-determined values (perhapsi) onto your list. Don't bother with code that is never executed because of the segfault (such as the call tol.pushpos()plus the definition ofpushpos()). Simplify until the bug has nowhere to hide. Your main function might just end up beingint main() { LinkedList l; l.push(0); }.