英文:
Finding an Element in a LinkedList - C++
问题
我正在尝试编写一个函数 find(Node* node, int valueInput),该函数从给定的节点开始,返回具有值 valueInput 的节点的索引,如果 valueInput 不存在则返回 -1。
以下是代码:
#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 == valueInput)
{
return count;
}
++count;
tempNode = tempNode->next;
}
return -1;
}
int main()
{
int valueInput, currentValue;
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 >> currentValue;
node1 = new Node();
node1->value = currentValue;
previous->next = node1;
previous = node1;
}
std::cout << find(head, valueInput);
}
目前,我的程序始终返回 -1。
示例输入和输出:
示例输入:
5
1->2->5
示例输出:
2
英文:
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
答案1
得分: 0
这是因为您的代码只有一个return -1
语句。您应该使用return count
而不是break
。此外,您始终与0
进行比较,而不是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;
}
您还应该使用nullptr
而不是NULL
。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论