Writing a function to do a head insert on a linked-list. It’s half working as in it’s inserting the object into head and reattaching the list but I’m losing my original head node in the list somehow.
If list is [green, red, blue] and I try to insert yellow, it will work but the new list will be [yellow, red, blue].
Node class is:
template<class T>
class Node
{
public:
Node(T theData, Node<T>* theLink) : data(theData), link(theLink){}
Node<T>* getLink( ) const { return link; }
const T& getData( ) const { return data; }
void setData(const T& theData) { data = theData; }
void setLink(Node<T>* pointer) { link = pointer; }
private:
T data;
Node<T> *link;
};
List is stored into a queue, so the head insert is a method of that class. Queue has private variables front and back that point to the corresponding positions of the list.
template<class T>
void Queue<T>::headInsert(T& theData)
{
Node<T> *temp;
temp = front->getLink();
front->setLink(new Node<T>(theData, temp->getLink() ));
front = front->getLink();
}
Your problem is in your
setLinkcall:You actually have a number of problems. First off, let’s suppose we have the following test list:
front = Red -> Green -> Blue -> NULLThe call
temp = front->getLink()yields the following output:temp = Green -> Blue -> NULL.The
new Node<T>(theData, temp->getLink())call, wheretheData = Yellow, then yields:new Node<T>(theData, temp->getLink())=Yellow -> Blue -> NULL.Calling
front->setLink(new(...)then gives you:front = Red -> Yellow -> Blue -> NULLLastly,
front = front->getLink():front = Yellow -> Blue -> NULL.This is not what you want. You simply want to take
yellowand pop it on the front of the list:No need to modify internal pointers. Just point front to be the new node containing your data, with it’s next pointer pointing to the old data.