2011-03-04 55 views
0
struct node 
{ 
    int data; 
    node* left; 
    node* right; 
}; 

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

我無法追蹤我犯了錯誤的地方,以及爲什麼它沒有出現while循環。無限循環:進程沒有正常終止

回答

0

如果你堅持遞歸版本,把while改爲if。遞歸

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

基礎:

  • 必須具備基本情況
  • 分解問題大小遞歸

如果你想在迭代的方式:

int secondlargest(node* a) 
{ 
    node* temp = a; 
    int data = -1; 
    while(temp != null){ 
     data = temp->data; 
     temp = temp->right; 
    } 
    return data; 
} 
+0

通常我在調用方法之前測試a == null,它使得該方法更加乾淨並避免未來調用的此測試,我知道它總是會失敗。 –

+0

是的,我弄錯了。謝謝! – Ava

1

你的錯誤是,你不應該使用一段時間,而是一個如果因爲它是遞歸的,但你想要什麼函數返回?最後一位成員的數據?如果是這樣的話,應該是這樣的:

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

OMG什麼一個失敗:(非常感謝! – Ava

+0

@vartika沒問題! –