1

I have a simple linked list node class which I can use to create a list 1->2->3 like so:

struct ListNode {
    int data_;
    ListNode *child_;
    ListNode(int data, ListNode *child) : data_{data}, child_{child} {}
};

ListNode node3(3, &node4);
ListNode node2(2, &node3);
ListNode head(1, &node2);

I want to make this construction less verbose by adding a new constructor, allowing something to the effect of:

ListNode head(1, (2, (3, nullptr)));

Essentially, I'd like the temporary objects created in the constructor to persist so I can point to them. How can I achieve this?

I've found an answer to a similar question here but I this doesn't handle the recursive structure in my class definition. I've been looking at move semantics but can't understand how to make it work with child being a pointer type.

Manas
  • 51
  • 3
  • You can't move `child_`, you can only move `data_` but moving an `int` is pointless. You have to copy the list if you want to do this recursively. A better way might be to support initializer lists so you can do `ListNode head{1,2,3};` You still have to allocate `ListNode`s for `2` and `3` but you skip having the temporary nodes. – Goswin von Brederlow Jul 19 '22 at 01:45
  • You should have a `class List` that has a `ListNode *head = nullptr;` and a constructor for `List{1,2,3}`. Would be cleaner that way. You can also improve a lot of functions if `List` has a `ListNode **tail = &head;`. – Goswin von Brederlow Jul 19 '22 at 01:49
  • 1
    This cannot be done, as described. C++ does not work this way. – Sam Varshavchik Jul 19 '22 at 01:49
  • Unlike L value references, R value references cannot be be used to initialize via constructor arguments. Only via aggregate initialization. – doug Jul 19 '22 at 01:54
  • Why not use `std::unique_ptr` instead of raw pointers, and create new nodes in the constructor? – Dmitry Kuzminov Jul 19 '22 at 02:35

1 Answers1

0

You would probably like to have the concept of a List to supplement your Node. In combination with an initializer_list this can get quite neat.

Something like

#include <iostream>

struct ListNode {
    int data_;
    ListNode *child_;
    ListNode(int data, ListNode *child) : data_{data}, child_{child} {}
};

struct List{
    ListNode* head = nullptr;
    List(std::initializer_list<int> list){
        for(auto val:list){
            insert(val);
        }
    }
    void insert(int value){
        head = new ListNode(value, head);
    }
};

now you can create it with something like

int main() {
    List list = {3, 2, 1};
}

See https://godbolt.org/z/sn6orf5h9

Now, there are plenty of improvements to be made here of course, some mentioned in the comments. But that was not what you were asking for.

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67