I have the following design for a List and Node class. I don't particularly care about execution efficiency here, so I'm using a recursive function rather than a simple loop.
shared_ptr<Node> Node::insert(int value) {
if (value == this->datavalue) {
// we have already seen this value: just count
datacount++;
return shared_from_this();
} else if (value < this->datavalue) {
// insert before current
auto newhead = shared_ptr<Node>( new Node(value) );
newhead->next = this->shared_from_this();
return newhead;
} else if (next == nullptr) {
// insert after current, and current is the tail
this->next = shared_ptr<Node>( new Node(value) );
return shared_from_this();
} else {
// insert after current, which is not the tail
auto newtail = next->insert(value);
this->next = newtail;
return shared_from_this();
}
};
void List::insert(int value) {
if (head == nullptr) // list is empty; make first node
head = shared_ptr<Node>( new Node(value) );
else // insert this value somewhere
head = head->insert(value);
};
I can not figure out how to use unique pointers here. The Node::insert routine returns shared_from_this in one case, or a new node in another case. So I would sort of need unique_from_this, which I know doesn't exist.
Can I maintain this design, or should I just write a big while loop over the list?
PS I should really use make_shared in the above.