Nieskończonej pętli: Proces nie zakończyła właściwie

głosy
0
struct node
{
    int data;
    node* left;
    node* right;
};

int secondlargest(struct node* a)
{
    while(a->right != NULL){
        secondlargest(a->right);
    }
    return a->data;
}

Nie jestem w stanie śledzić gdzie zrobiłem błąd i dlaczego jej nie wychodzi z pętli while.

Utwórz 04/03/2011 o 02:35
źródło użytkownik
W innych językach...                            


2 odpowiedzi

głosy
1

Twój błąd to, że nie należy korzystać z czasu, ale zamiast tego, czy dlatego, że jest rekurencyjna, ale to, co chcesz, że funkcja zwraca? dane z ostatniego członka? jeśli tak, to powinno być tak:

int secondlargest(struct node* a) {
   if(a == NULL) return -1;
   secondlargestr(a);
}

int secondlargestr(struct node* a) {
   if(a->right!=NULL) return secondlargest(a->right);
   return (a->data);
}
Odpowiedział 04/03/2011 o 02:41
źródło użytkownik

głosy
0

Jeśli nalegać na wersji rekurencyjnej, zmiany czasu, aby jeśli.

int secondlargest(node* a)
{
    if(a == null){
        // if the first node is already NULL
        return -1;
    }
    if(a->right == NULL){
        return a->data;
    }else{
        return secondlargest(a->right);
    }
}

Podstawy rekurencji:

  • Musi mieć wariant podstawowy
  • Załamać rozmiaru problemu rekurencyjnie

Jeśli chcesz iteracyjny sposób:

int secondlargest(node* a)
{
    node* temp = a;
    int data = -1;
    while(temp != null){
        data = temp->data;
        temp = temp->right;
    }
    return data;
}
Odpowiedział 04/03/2011 o 02:42
źródło użytkownik

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more