Nekonečné smyčky: Proces není správně zastavení

hlasů
0
struct node
{
    int data;
    node* left;
    node* right;
};

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

Nejsem schopen sledovat, kde jsem udělal chybu a proč to není pocházející z cyklu while.

Položena 04/03/2011 v 02:35
zdroj uživatelem
V jiných jazycích...                            


2 odpovědí

hlasů
1

Vaše chyba je, že byste neměli používat nějakou dobu, ale místo toho, jestli proto, že je rekurzivní, ale co chceš funkce vrátit? údaje o posledním členem? pokud ano, to by mělo být takhle:

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);
}
Odpovězeno 04/03/2011 v 02:41
zdroj uživatelem

hlasů
0

Pokud trváte na rekurzivní verzi změnit chvíli, pokud.

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);
    }
}

Základy rekurze:

  • Musí mít základní případ
  • Rozebrat velikosti problému rekurzivně

Pokud chcete, aby iterativní způsobem:

int secondlargest(node* a)
{
    node* temp = a;
    int data = -1;
    while(temp != null){
        data = temp->data;
        temp = temp->right;
    }
    return data;
}
Odpovězeno 04/03/2011 v 02:42
zdroj uživatelem

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