#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int Data)
{
data = Data;
next = NULL;
}
};
//This FUNCTION is used to return the index value of the integer we trying to find
int index(Node *head, int find)
{
Node *temp = head;
int count = 0;
while (temp != NULL)
{
temp = temp->next;
count ;
if (temp->data == find)
{
return count;
}
else
{
// It should return -1 only when it doesn't find the particular variable
return -1;
}
}
}
Idk why but it is always return -1 as value and I am not able to understand.
CodePudding user response:
What happens if the first node does contain the value that you want? Does it return 0?
Your conditional statement always results in a return statement, so it will return 0 if the first Node contains the value that you want, -1 if it does not.
CodePudding user response:
You put your return -1 as the else condition when the current node you're inspecting doesn't match what you're looking for. What you really want to do is return -1 after you've exhausted all the nodes (i.e. after your while loop)
It also makes the function more correct as it would return a value in all circumstances. At the moment if you pass NULL for head you haven't defined what should happen.
