簡體   English   中英

為什么我得到零而不是 1?

[英]why i'm getting zero instead of 1?

這是一個使用遞歸從鏈表中搜索數字的程序。

#include <iostream> 

using namespace std; 

class node { 
public: 
    int data; 
    node *next; 

    void create(int *,int); 
    int max(node*,int); 
}; 

node *first; 

void node::create(int a[],int n) { 
    first = new node; 
    first->data = a[0]; 
    first->next = NULL; 
    node *last = first; 
    for (int i = 1; i < n; i++) {
        node *t = new node; 
        t->data = a[i]; 
        t->next = NULL; 
        last->next = t; 
        last = t; 
    }
} 

int node::max(node *l, int p) { 
    if (l->data == p) { 
        return 1;
    } 
    if (l == 0) 
        return 0; 
    else {  
        max(l->next, p); 
        return 0;
    }
} 

int main() { 
    int a[5] = {1,2,3,4,5}; 
    node m; 
    m.create(a,5); 
    cout << m.max(first, 3); 
    return 0; 
}

直覺。 取而代之的是:

else {  
    max(l->next, p); 
    return 0;
}

這個:

else {  
    return max(l->next, p); 
}

或者更好的是,讓我們修復整個max函數以在取消引用l之前檢查 null。

int node::max(node *l, int p) { 
    int result = 0;
    if (l != nullptr) {
       if (l->data == p) {
           result = 1;
       }
       else {
          result = max(l->next, p);
       }
    }
    return result;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM