I am trying to create both a minimum heap and a linear linked list to store values in order, listing the amount of comparisons that take place in each of them. My program keeps crashing though when inserting values into my linked list. Can someone help point out what I am doing wrong. VS debugger shows that it can't read the info in tempPtr in line 89, but I can't seem to get it working.
template<class T>
void List<T>::insertNode(T newValue)
{
ListNode* newNode; //Pointer for the new node.
ListNode* nodePtr; //Pointer to traverse the list.
//Allocates a new node and stores newValue in it.
newNode = new ListNode;
newNode->value = newValue;
newNode->nextNode = NULL;
//If there are no nodes, the new node will be made the first one in the list.
if (!head)
{
head = newNode;
}
//Otherwise the program will loop to the list's end and add the node.
else
{
//Starts at the list's head.
nodePtr = head;
//Loops through the list looking for the end.
while (nodePtr->nextNode && newValue >= nodePtr->value)
nodePtr = nodePtr->nextNode;
//Adds the node.
nodePtr->nextNode = newNode;
//Increment length.
length++;
}
}
The while loop at line 26 looks correct, go until the end of the list or the new value is less than the current value.
However, your addition of the node ( line 30 ) does not connect the new node's next to the nodePtr's next. Line 95 and line 96 of your old code is needed.
nodePtr is certain to exist, so nothing fancy is needed:
1 2
newNode->nextNode = nodePtr->nextNode; // fine if nodePtr->nextNode == 0
nodePtr->nextNode = newNode;
Ok, I see where I went wrong with that. However, the list is supposed to be stored in order (smallest to highest), which I though that my newValue >= nodePtr->value (line 26) would make sure of that, but it isn't storing them in that order. Did I mess up the sign or something else?