Wrote this program in Cpp for Linked Lists. I am getting an error in insert when trying to insert at the front of the linked list as a segmentation fault. I couldn't print the list with list.printList()
, but if I use push_back()
and then printList()
, it works fine. Spent a lot of time pondering but couldn't figure out? Please help me!
#include<iostream>
using namespace std;
class Node {
private:
int data;
Node* next;
public:
Node() {
data = 0;
next = NULL;
}
void setData(int data) {
this->data = data;
}
int getData() {
return data;
}
void setNextNode(Node* node) {
this->next = node;
}
Node* getNextNode() {
return next;
}
};
class LinkedList {
private:
Node Head_node;
public:
void createList(int n) {
int x;
cin >> x;
Head_node.setData(x);
n--;
while (n) {
cin >> x;
push_back(x);
n--;
}
}
Node* lastNode() {
Node* temp = &Head_node;
while ( (*temp).getNextNode() != NULL) //while is not last node
{
temp = (*temp).getNextNode();
}
return temp;
}
void push_back(int x) {
Node* temp = lastNode(); //move to last node
Node* a = new Node; // create a new node
(*temp).setNextNode(a); //link new node to list
(*a).setData(x); //set new node data
}
void push_front(int x) {
Node* a = new Node;
(*a).setData(x);
Node join = Head_node;
(*a).setNextNode(&join);
this->Head_node = (*a);
}
void printList() {
Node* temp = &Head_node;
do {
cout << (*temp).getData() << " ";
temp = (*temp).getNextNode();
} while (temp != NULL);
}
};
int main() {
int n;
cin >> n;
LinkedList list;
list.createList(n);
list.push_front(29);
list.printList();
return 0;
}
I ran code and it said "segmentation fault"
But if I run list.push_back(29); list.printList();
instead, everything is still fine!