Im trying to make a linked list where the user has to enter in the values on their own in the console and then they show in the linked list. After entering the first value it shows an error "signal: segmentation fault (core dumped)", how do i fix it. Im a begginer at c++ so i really have no idea of how to fix this, all help is greatly appreciated. Heres the code:
#include <iostream>
using namespace std;
class Node{
public:
int value;
Node *next;
public:
Node(int value, Node *next = nullptr) {
this->value = value;
this->next = next;
}
int getValue() {return this->value;}
Node *getNext() {return this->next;}
void setNext(Node*next) {this->next = next;}
};
class LinkedList {
private:
Node *head;
public:
LinkedList() {
this->head = nullptr;
}
~LinkedList() {
while(this->head != nullptr) pop();
}
friend std::ostream & operator <<(std::ostream &os, const LinkedList &rhs) {
for(Node *curNode = rhs.head; curNode != nullptr; curNode = curNode->getNext()) {
os << curNode->getValue();
if (curNode->getNext() != nullptr) os << "";
}
return os;
}
void push(int value) {
this->head = new Node(value, this->head);
}
int pop() {
int value;
if (this->head != nullptr) {
value = this->head->getValue();
Node *temp = this->head;
this->head = this->head->getNext();
delete temp;
} else {
throw std::range_error("List is empty!");
}
return value;
}
};
void append(Node** head_ref, int new_data)
{
Node* new_node = new Node((*head_ref)-> value);
Node *last = *head_ref;
new_node->value = new_data;
new_node->next = NULL;
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
while (last->next != NULL)
{
last = last->next;
}
last->next = new_node;
return;
}
void printList(Node* n)
{
while (n != NULL) {
std::cout << n->value << " ";
n = n->next;
}
}
int main()
{
Node* head = NULL;
int a;
cout << "Please enter value 1#: ";
cin >> a;
append(&head, a);
int b;
cout << "Please enter value 2#: ";
cin >> b;
append(&head, b);
int c;
cout << "Please enter value 3#: ";
cin >> c;
append(&head, c);
int d;
cout << "Please enter value 4#: ";
cin >> d;
append(&head, d);
int e;
cout<<"Created Linked list is: ";
printList(head);
return 0;
}