我正在编写一个方法,用于在c++中删除排序链表中的重复值节点。我尝试使用Node*而不是void return类型,但由于return语句而面临错误。
我的方法代码..
Node* RemoveDuplicates(Node *head)
{
struct Node* current = head;
struct Node* next_next;
if(current == NULL)
return;
while(current->next != NULL)
{
if(current->data == current->next->data)
{
next_next = current->next->next;
free(current->next);
current->next = next_next;
}
else
{
current = current->next;
}
}
}我收到的编译时错误消息..
solution.cc: In function 'Node* RemoveDuplicates(Node*)':
solution.cc:31:6: error: return-statement with no value, in function returning 'Node*' [-fpermissive]
return ;
^发布于 2014-06-25 12:51:44
将返回类型更改为void。
该函数不会返回任何有价值的内容。
发布于 2014-06-25 13:43:53
编译器不会假装知道你在想什么,他会要求你就正在发生的事情签订合同。因此,声明返回类型Node*时,必须提供该特定类型的输出:节点指针。我能想象的最有可能的情况是返回当前节点,而不是函数末尾的重复项。
Node* RemoveDuplicates(Node *head)
{
// some instructions
return head;
}所以你可以有这样的语义:
Node* distinctList = RemoveDuplicates(head);
if (distinctList) // NULL (0 / false) if empty
{
// some more instructions
}然而,如果你不需要任何东西就可以从函数中取出,那么返回类型应该是void (nothing)。
希望这能有所帮助!
发布于 2014-06-25 16:55:24
我将把这当作一个学习练习,忽略这样一个事实:使用std列表比实现您自己的链表更可取,使用new和delete比使用malloc和free更可取。
如果将Node*指定为返回类型,则必须返回指向节点的指针。为了回答你的问题,你必须问:你想返回什么指针?正如你所写的,你正在删除所有重复的指针。是否要返回已删除的最后一个指针?是否要循环,直到找到重复项并将其删除?
您的代码片段中有两个出口点。第一个是简单的"return“语句,当列表为空时调用该语句。正如你所写的,你返回的是void,也就是什么都没有。您需要返回一个指向节点的指针,但是没有有效的指针,所以您可能希望返回一个null_ptr,它是一个空指针。
现在我们来看你的问题,这部分取决于你想要的行为。例如:
while(current->next != NULL)
{
if(current->data == current->next->data)
{
next_next = current->next->next;
free(current->next);
current->next = next_next;
/// Here you have a valid pointer you could return:
return current;
}
else
{
current = current->next;
}
// if you get here, no duplicates were found, so you can return a nullptr.
return std::nullptr;
}将遍历列表,直到找到重复项,删除重复项,并返回指向剩余指针的指针。如果没有找到重复项,则返回nullptr。
我将其保留为exersize来修改它,以循环遍历列表中的所有元素,直到找到最后一个重复的元素(提示,您必须引入一个局部变量来存储返回值),然后返回该变量。
祝好运。
https://stackoverflow.com/questions/24400391
复制相似问题