Внутренний цикл while
написан неправильно.
while(current != NULL){
Node* find = current;
a = target - current->data;
while(find != NULL){
find = find->next;
// PROBLEM
// At some point find will be NULL. By dereferncing a NULL
// pointer, your code enters into undefined behavior territory.
if(find->data == a){
cout <<"Yes there are 2 values that add to get the target."<<endl;
cout << a <<endl;
cout << current->data <<endl;
return;
}
}
current = current->next;
}
Я предлагаю изменить этот блок кода на:
while(current != NULL){
a = target - current->data;
Node* find = current->next;
while(find != NULL){
if(find->data == a){
cout <<"Yes there are 2 values that add to get the target."<<endl;
cout << a <<endl;
cout << current->data <<endl;
return;
}
find = find->next;
}
current = current->next;
}
Мое личное предпочтение - использовать for
loop.
for ( ; current != NULL; current = current->next )
{
a = target - current->data;
for ( Node* find = current->next; find != NULL; find = find->next )
{
if(find->data == a)
{
cout <<"Yes there are 2 values that add to get the target."<<endl;
cout << a <<endl;
cout << current->data <<endl;
return;
}
}
}
Предложение по очистке
Использование
Node* current = new Node;
вызывает утечку памяти. Это также неверно, когда список пуст. Тебе это не нужно. Вот очищенная версия функции.
void LinkedList::FindSum(int target){
int a = 0;
if(head == NULL)
{
cout<<"The list is empty."<<endl;
}
for ( Node* current = head; current != NULL; current = current->next )
{
a = target - current->data;
for ( Node* find = current->next; find != NULL; find = find->next )
{
if(find->data == a)
{
cout <<"Yes there are 2 values that add to get the target."<<endl;
cout << a <<endl;
cout << current->data <<endl;
return;
}
}
}
cout << "The 2 values were not found."<<endl;
}