I am implementing a linked list. There is a problem: when I change a pointer inside a function, the change is not visible outside of the function.
#include<bits/stdc++.h>
using namespace std;
//define
class List{
public:
int data;
List *next;
public:
List(int n){
this->data=n;
this->next=NULL;
}
};
void add(List *head,int data){
List * nn = new List (data);
head=nn;
}
// driver code
int main(){
List *head=NULL;
List * nn = new List (45);
head=nn;
cout<<head->data;
return 0;
}
This code is printing 45.
class List{
public:
int data;
List *next;
public:
List(int n){
this->data=n;
this->next=NULL;
}
};
void add(List *head,int data){
List * nn = new List (data);
head=nn;
}
// driver code
int main(){
List *head=NULL;
add(head,45);
cout<<head->data;
return 0;
}
This program prints nothing. It simply crashes.