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.
Asked
Active
Viewed 716 times
1
-
5You can't. Use pointers. – M.M May 17 '16 at 05:00
-
@lightrek Have you considered using smart pointers. Like unique_ptr? – bashrc May 17 '16 at 05:09
-
Possible duplicate of [Is a Linked-List implementation without using pointers possible or not?](http://stackoverflow.com/questions/3002764/is-a-linked-list-implementation-without-using-pointers-possible-or-not) – ibezito May 17 '16 at 05:10
-
Linked List is a dynamic data structure and reference is compile time construct. So, you cannot use reference to implement linked list in very basic way. – sameerkn May 17 '16 at 05:14
-
3A Java reference is much more similar to a C++ pointer than to a C++ reference. They're different languages, they use different terminology. – Benjamin Lindley May 17 '16 at 05:16
-
3References in `Java` are like *pointers* in `C++` so use *pointers*. – Galik May 17 '16 at 05:17
-
The problem is not so much that a reference can't be null, than that a reference can't be reassigned. – MikeMB May 17 '16 at 07:18
2 Answers
2
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.
2
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!

Eissa N.
- 1,695
- 11
- 18
-
While your answer is correct. It may be beyond the understanding of OP, who isn't well aware of pointers/references in C++. No offense to anyone! – Ajay May 17 '16 at 06:57
-