Answer the question
In order to leave comments, you need to log in
How to implement search in Linked List?
I have a Node class
class Node {
public:
int value;
Node* next = NULL;
};
bool find(Node* node, int element) {
if(node -> value == element) return true;
else if(node -> value) return find(node -> next, element);
else return false;
}
Failed test #1. Wrong answer
Input:
2
0 -> 1 -> 2 -> 3 -> 4 -> 5
Your output:
false
Correct output:
true
Answer the question
In order to leave comments, you need to log in
bool find(node* n, int value)
{
node* ptr = n;
while(ptr != nullptr)
{
if(ptr->value == value) return true;
ptr = ptr->next;
}
return false;
}
node* find(node* n, int value)
{
node* ptr = n;
while(ptr != nullptr)
{
if(ptr->value == value) return ptr;
ptr = ptr->next;
}
return ptr;
}
node* result = find(...);
if(result)
{
//...
}
What am I doing wrong?Don't debug your program. If you don't know how to use a debugger, then take a sheet of paper, a pencil, and go through your entire program step by step.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question