I'm getting a segmentation fault when I try to search a linkedlist using the following description:
//! Searches for the first occurrence of value v that appears in the list
//! after node n
//!
//! @param v The value being searched for
//! @param n The node in the list after which the search should begin.
//! If n is NULL, the list should be searched from the beginning.
//!
//! @return a pointer to the node containing v, or NULL if v is not found
LLNode * Find(const std::string & v, LLNode * n) const;
I have tried setting a current node to head so I can start from the beginning and search the whole linkedlist when I encounter a null as the value of n.
As so
LLNode * LinkedList::Find(const std::string & v, LLNode * n) const
{
LLNode * current = n;
if(current==NULL)
{
current = this->GetFirst();
{
while(current != NULL)
{
if(current->value == v) {
cout << "Actual: " << current->value << "\tExpected: " << v << endl;
return current;
}
else
current = current->next;
}
}
}
else {
while(current != NULL)
{
if(current->value == v) {
cout << "Actual: " << current->value << "\tExpected: " << v << endl;
return current;
}
else
current = current->next;
}
}
return NULL;
}
If I don't use the if else statement like so:
if(current==NULL)
{
......
}
else
{
....
}
and have just one while loop no segmentation fault occurs but it return null when it is not suppose to. I'm really stumped. I can't see how I could include the requirement of if the current node is null then just start from the beginning.
Your help is greatly appreciated.