First of all, note that you've inverted the semantics of insert(). insert() should add the new node before the existing one, not after. |
I'm glad you brought that up, because I DID note that! In fact, I made a note of it in the book. I saw Stroustrup said it, then I saw him use it as he did previously to add to the end of the list. I myself said, "Shouldn't this be called add() ?" which Stroustrup himself says in the paragraph DIRECTLY after the definition, but since that's how he used it, I thought, "Sure, OK then..."
And it's at THIS point that I have to stop you and ask: if I use the function (I defined) purely as an add() function, which is what I originally wanted to do (adding to the end of the list, then tying my links together and leaving current->next = nullptr to mark the end of the list) does what you say about dangling references still apply? Because that really was my original intent, and what I assumed Stroupstrup was going for too, which added (and still adds) to the confusion. Here is his original code that he (rightly) said was too verbose to be useful:
1 2 3 4 5
|
Link* norse_gods = new Link{"Thor",nullptr,nullptr};
norse_gods = new Link{"Odin",nullptr,norse_gods};
norse_gods–>succ–>prev = norse_gods;
norse_gods = new Link{"Freia",nullptr,norse_gods};
norse_gods–>succ–>prev = norse_gods;
|
//back to his insert definition, followed by...
"Given that, we could write:"
1 2 3
|
Link* norse_gods = new Link{"Thor"};
norse_gods = insert(norse_gods,new Link{"Odin"});
norse_gods = insert(norse_gods,new Link{"Freia"});
|
You see where my confusion comes from? He's using his insert() function in the way I thought an add() function was supposed to be used, so I assumed that's what he wanted, and where I derived my code.
I DO get what you're saying though! If current were to come in the middle of an existing list:
existing->link = (something)
current->prev = existing;
current->prev->next = current;
//UH OH! Now you've lost everything from current, which now is the new end of the list.
When if I were REALLY defining an insert function and wanted to put current after existing and before what was already there, I would (probably) want something like...
[Existing] -> [Something Else]
Want...
[Current] -> [Existing] -> [SE]
1 2 3 4 5 6
|
//Check Current and Existing for null... probably SE too...
if(existing->prev) current->prev = existing->prev;
current->prev->next = current;
current->next = existing;
existing->prev = current;
return current; //I think?
|
I really need to go back and give this section a sixth or so read. It's all so confusing.