Adding a value to our list means constructing a new node and inserting it into the existing chain of nodes. The natural place to insert a new node is at the start of the list, as that is the easiest place to access.
void SimpleLinkedList<T>::insertStart(T value) {
// allocate new node on the heap. Store the address in "newNode"
ListNode<T>* newNode = new ListNode<T>(value);
// set the list's head pointer to point to the new node
head = newNode;
}
When we leave insertStart, the newNode variable goes out of scope. But the node it was pointing to is still allocated on the heap, and the listβs head pointer is still pointing to it. So the list still has access to the new node.
But what if there is already something pointed at by head? Consider the figure below. We have started the insert process and created a new node to store the value 6. But head is already pointing to a node containing 10. We donβt want to just change head to point to the new node, because then we would lose track of the 10 node:
template <typename T>
void SimpleLinkedList<T>::insertStart(T value) {
// allocate new node on the heap. Store the address in "newNode"
ListNode<T>* newNode = new ListNode<T>(value);
// set the new node's next pointer to point to the old first node
newNode->next = head;
// set the list's head pointer to point to the new node
head = newNode;
}
This handles both the empty and non-empty list cases. If the list is empty, then head is nullptr, so the line newNode->next = head; sets the new nodeβs next pointer to nullptr, which is correct for a one-item list. If the list is not empty, then head points to the old first node, and we set the new nodeβs next pointer to point to that old first node. We should end up with something that looks like this:
You can click and drag on the animation area to pan around. Use the Ctrl + mouse wheel (or touchpad scroll gesture) while over the animation area to zoom in and out.
Build an alternate version of the insertStart function that correctly inserts a new node at the beginning of the list. You will not use all the blocks.