K
K
keddad2019-02-08 15:42:22
C++ / C#
keddad, 2019-02-08 15:42:22

How to implement search in Linked List?

I have a Node class

class Node {
    public:
        int value;
        Node* next = NULL;
};

And a function that should run through this Linked List in search of the desired element:
bool find(Node* node, int element) {
    if(node -> value == element) return true;
    else if(node -> value) return find(node -> next, element);
    else return false;
}

But it fails the first test:
Failed test #1. Wrong answer
Input:
2
0 -> 1 -> 2 -> 3 -> 4 -> 5
Your output:
false
Correct output:
true

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2019-02-08
@keddad

Condition
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)
{
    //...
}

R
Rsa97, 2019-02-08
@Rsa97

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.
If nothing helps
node->value на первом же элементе равняется нулю, соответственно отрабатывает последняя ветка условия и возвращает false.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question