Hi.
I have been scratching my head trying to find out why I am getting a crash every time I try to use the insert() method in a Linked List template class I am working on.
Here is the code I have for the insert method in question.
template <typename T>
void LinkedList<T>::Insert(T value){
//traverse the list and ADD a given value
//dynamically allocate mem and create new node
ListNode *NewNode = new ListNode;
NewNode->data = value;
NewNode->next= NULL;
//check if our first pointer has a value, if not... point to our new node
if(first == NULL){
first=NewNode;
}
else{
//initialize current pointer to start of our list
ListNode *current= first;
//initialize a previous pointer
ListNode *prev= NULL;
//traverse our list to the insert location
while (current->data < value && current->next !=NULL){
prev = current;
current = current->next;
}//we should now be at our insertion location
//update our pointers
prev -> next = NewNode;
NewNode -> next = current;
}
//increment size
ListSize++;
}
What is going wrong? I traced the code (drew it out on paper) and I don't see how it is crashing. Inserting the first value (as I am testing) should just be running the following portion, right?:
ListNode *current= first; // only 1 value in list which is first
ListNode *prev= NULL;
while (current->data < value && current->next !=NULL){
prev = current; // this never gets called as current->next is NULL
current = current->next;
}
prev -> next = NewNode; // prev is invalid so exception happens here
lol... I must be thinking too hard at this point or something.
Guess I will have to go back to basics and hit up some tutorial videos or something. Hopefully it magically makes full sense before Monday.