简体   繁体   中英

Finding an Element in a LinkedList - C++

I am trying to write a function find(Node* node, int valueInput) that starts at the given node and returns the index of the node with the value valueInput, and return -1 if valueInput does not exist.

Here is the code

#include <iostream>

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

int find(Node* node, int valueInput)
{
    Node* tempNode = node;
    int count = 0;
    while (tempNode != NULL)
    {
        if (tempNode->value == 0)
        {
            break;
        }
        ++count;
        tempNode = tempNode->next;
    }
    return -1;

}

int main()
{
    int valueInput, currentValue;
    int listValues;
    char arrow;
    Node* node1, * previous, * head;
    std::cin >> valueInput;
    std::cin >> currentValue;
    node1 = new Node();
    node1->value = currentValue;
    node1->next = NULL;
    previous = node1;
    head = node1;
    while (std::cin)
    {

        std::cin >> arrow;
        std::cin >> arrow;
        std::cin >> currentValue;
        node1 = new Node();
        node1->value = currentValue;
        previous->next = node1;
        previous = node1;
    }
    std::cout << find(head, valueInput);

}

Currently, my program returns -1 always Sample input and outputs:

Sample Input: 5 1->2->5

Sample Output: 2

That's because your code only has a return -1 statement. You should return count instead of break . Also, you are always comparing against 0 instead of the valueInput

int find(Node* node, int valueInput)
{
    Node* tempNode = node;
    int count = 0;
    while (tempNode != nullptr)
    {
        if (tempNode->value == valueInput)
        {
            return count;
        }
        ++count;
        tempNode = tempNode->next;
    }
    return -1;
}

You should also be using nullptr instead of NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM