I am trying to implement a singly linked list.. I am executing the code on terminal and i get the Segmentation fault (core dumped). I dont understand why is it happening? I read the other answers for the same and unfortunately none of them helped..
Any help will be appreciated..Please explain where did it went wrong? Thanks!
//singly linked list
#include<iostream>
using namespace std;
class node
{
int data;
node *next;
public:
node() //constructor
{
data=0;
next=NULL;
}
void setdata(int x)
{
data=x;
}
void setnext(node *x)
{
next=x;
}
int getdata()
{
return data;
}
node* getnext()
{
return next;
}
};
class list
{
node *head;
public:
list() // constructor
{
head=NULL;
}
void firstnode(int x)
{
node *temp;
temp=new node;
temp->setdata(x);
temp->setnext(head);
head=temp;
}
void insertbeg(int x)
{
node *temp1;
temp1=new node; //Allocate memory to temp1
temp1->setdata(x); // set data in new node to be inserted
temp1->setnext(head); // new node points to previous first node
head=temp1; // head now points to temp1
}
void insertbet(int x,int y)
{
node *temp1;
node *temp2;
temp1=new node; // Allocate memory to temp1
temp2=new node; // Allocate memory to temp2
temp1=head; // point temp1 to head so both of them point to first node
for(int i=0;i<y;i++) // To reach the desired node where data is to be inserted
{
temp1->getnext(); // point to next of node pointed by temp
temp1=temp1->getnext(); // temp1 now contains address of node pointed by next
}
temp2->setdata(x);
temp2->setnext(temp1->getnext()); // insert new node in list
temp1->setnext(temp2); // points the y-1 node to new node
}
void insertend(int x)
{
node *temp1;
node *temp2;
temp1=new node;
temp2=new node;
temp1=head;
while(temp1!=0)
{
temp1=temp1->getnext();
}
temp2->setdata(x);
temp1->setnext(temp2);
temp2->setnext(NULL);
}
void print()
{
node *temp1;
temp1=new node;
temp1=head;
while(temp1!=0)
{
cout<<temp1->getdata()<<endl;;
temp1=temp1->getnext();
}
}
};
int main()
{
list l;
l.firstnode(4);
l.insertbeg(3);
l.insertbeg(4);
l.insertbeg(6);
l.insertend(45);
l.insertend(9);
l.insertbet(2,46);
l.print();
return 0;
}
edit:Sorry guys i am new to coding, i am trying to debug with little progress. I already read the question,the answer is too broad, i need something specific to solve the error.