Your code from your textbook is seemingly trying to engrain one-track purpose rather than encompassing what you should be thinking about, namely managing the list.
- This step wires the new node to the
next
pointer of the current end of list node.
- This step establishes a new end of list.
That said, the linked list in this code is emulating a queue, where firstPtr
always points to the "front" of the queue, and lastPtr
always points to the "back" of the queue where the new arrivals go. If one is NULL, they both better be. Thus you can assume:
if (lastPtr == NULL) // if this is true, the list is empty.
Thus consider this upon a new arrival:
- If the list is empty, both
firstPtr
and lastPtr
should point to the new node.
- Otherwise,
firstPtr
remains unchanged and lastPtr->next
is set to the new node, then lastPtr
is set to the new node.
Note that in both of these cases, lastPtr
is going to reference the new node when finished. therefore the entire thing becomes:
if (lastPtr == nullptr)
firstPtr = newPtr; // list is empty, first must point to new arrival
else
lastPtr->next = newPtr; // list is not empty, wire to end of list
lastPtr = newPtr; // regardless, establish new end-of-list
Removing nodes is somewhat similar, btw.
if (firstPtr != nullptr)
{
victim = firstPtr;
firstPtr = firstPtr->next;
delete victim;
if (firstPtr == nullptr)
lastPtr = nullptr;
}
A picture speaks a thousand words. The following actions will generate the corresponding diagrams:
- Start with an empty list
- Add NODE0
- Add NODE1
- Add NODE2
- Remove NODE0
- Add NODE3
- Remove NODE1
- Remove NODE2
- Remove NODE3
1. Start with an empty list
firstPtr ----> NULL
lastPtr ----> NULL
2. Add NODE0
firstPtr ------> NODE0 ---> NULL
|
lastPtr ------------
3. Add NODE1
firstPtr ----> NODE0 ---> NODE1 ----> NULL
|
lastPtr ---------------------
4. Add NODE2
firstPtr ----> NODE0 ---> NODE1 ----> NODE2 ----> NULL
|
lastPtr ---------------------------------
5. Remove NODE0
firstPtr ----> NODE1 ----> NODE2 ----> NULL
|
lastPtr ----------------------
6. Add NODE3
firstPtr ----> NODE1 ----> NODE2 ----> NODE3 ----> NULL
|
lastPtr ----------------------------------
7. Remove NODE1
firstPtr ----> NODE2 ----> NODE3 ----> NULL
|
lastPtr ----------------------
8. Remove NODE2
firstPtr ----> NODE3 ----> NULL
|
lastPtr ----------
9. Remove NODE3
firstPtr ----> NULL
lastPtr ----> NULL
I honestly can't think of a better way to express it.