In Java, a reference can be initialized to null. However, in C++, it will cause a problem. So not sure how to use reference-only to implement the linked list.
2 Answers
I don't know how useful the concept is, but you CAN do it using std::reference_wrapper, as follows:
#include <iostream>
#include <list>
#include <functional>
using namespace std;
int main() {
int a = 2, b = 6, c = 1;
list<reference_wrapper<int>> mylist;
mylist.push_back(a);
mylist.push_back(b);
mylist.push_back(c);
for(auto x : mylist) {
cout << x << " ";
}
cout << endl;
a = 3; // <- this setting will modify mylist!
for(auto x : mylist) {
cout << x << " ";
}
return 0;
}
I would recommend learning C++ ways of handling things, specially that you are coming from Java world. Demo!
Im not sure why you would want to use references in c++ since a reference cannot be null in C++ like you said. What would you do if you get to the end of the linked list.
Your only solution (Since you are new to c++) is to use pointers like this.
struct Node{
int value;
Node* next;
}
This way you can leave the pointer called next as null and that would signify the end of the linked list.
Javaare like pointers inC++so use pointers.