Почему моя функция не выводит последний оператор, когда условие if внутри цикла while оказывается ложным? - PullRequest
0 голосов
/ 10 октября 2019
void LinkedList::FindSum(int target){
    int a =0;
    Node* current = new Node;


    if(head != NULL)
    {
        current = head;
    }
    else
    {
        cout<<"The list is empty."<<endl;
    }


    while(current != NULL)
    {
        Node* find = current;
        a = target - current->data;
        while(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;
        }
    }
       current = current->next;
   }


    cout << "The 2 values were not found."<<endl;

}

Это следующий код для моей функции, когда она применяется в main и оказывается ложной, она не преграждает последнее утверждение, и я не могу понять, почему.

Ответы [ 2 ]

1 голос
/ 10 октября 2019

Внутренний цикл 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;
}
0 голосов
/ 10 октября 2019

Вы использовали return внутри оператора if- . Если ваш код что-то возвращает, то после возврата в первый раз код заканчивается там, и коды после этого оператора return не будут выполняться.

...