I’m creating a Linked List program and I currently have this method to insert an item into the front of the list:
template <class T>
void LinkedList<T>::insert(T *o)
{
node newNode;
newNode.o = o;
newNode.next = first;
newNode.prev = NULL;
first->prev = &newNode;
first = &newNode;
}
where I have a struct as follows:
struct node {
node *next;
node *prev;
T *o;
};
I think my logic is right for the insert method; however, I feel as if I’m not doing it properly, specifically dealing with the pointers. I feel as if I have to many newNode. lines and that I could do this better somehow. Any suggestions or is it right?
Note: I’m new to C++ so please be kind. I know this is a simple question
newNodeis local toinsert()and will be destructed when that method returns, meaningfirst->prevandfirstwill be pointing to anodethat no longer exists.Use
new: