Search code examples
c++recursionlinked-listlinear-search

why i'm getting zero instead of 1?


This is a program of searching a number from linked list using recursion.

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

Solution

  • Hunch. Instead of this:

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

    This:

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

    Or better yet, let's fix the whole max function to check for null before dereferencing l as well.

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