1

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.

7
  • 5
    You can't. Use pointers. Commented May 17, 2016 at 5:00
  • @lightrek Have you considered using smart pointers. Like unique_ptr? Commented May 17, 2016 at 5:09
  • Possible duplicate of Is a Linked-List implementation without using pointers possible or not? Commented May 17, 2016 at 5:10
  • 3
    A Java reference is much more similar to a C++ pointer than to a C++ reference. They're different languages, they use different terminology. Commented May 17, 2016 at 5:16
  • 3
    References in Java are like pointers in C++ so use pointers. Commented May 17, 2016 at 5:17

2 Answers 2

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!

Sign up to request clarification or add additional context in comments.

2 Comments

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 I agree. But, I just wanted to show possibilities :)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.