#include <iostream>
#include <string>
using namespace std;
struct Node{
Node *next;
int data;
};
int main(){
Node* head = NULL;
int data;
cin >> data;
Node*m = head;
while(data >0){
cout <<"enter a data";
cin >> data;
m -> data = data;
m -> next = m;
}
while(m -> next != NULL){
cout << m -> data << endl;
}
return 0;
}
Here is simple code that takes values when they are greater than 0 and make a linked list. after you enter a negative value, the while loop is terminated and prints the values.
However, the code gives me segmentation fault when it asks enter a data and after it takes the data. I could not solve it, what is the reason?
You get uninitialized pointer here. If you define link to next node as
Node *next;you should initialise pointer with address to valid Node object before use.And
as you can see, you trying to call member
dataof NULL object.How to fix it:
Anways initialize pointer with valid address. For example: