【发布时间】:2018-02-09 15:33:01
【问题描述】:
我正在做这个hackerrank问题(https://www.hackerrank.com/challenges/get-the-value-of-the-node-at-a-specific-position-from-the-tail) 我的代码如下-
int GetNode(Node *head,int positionFromTail)
{
Node *prev = NULL;
Node *current = head;
Node *next;
while(current!=NULL){
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
int p=0;
while(head->next!=NULL){
if(p== positionFromTail){
return head->data;
}
else {
p++;
head= head->next;
}
}
}
所以我所做的是,我首先反转了链表,然后循环查找特定位置,然后打印它的值。这是正确的方法吗? 它给了我这个错误。
solution.cc: In function ‘int GetNode(Node*, int)’:
solution.cc:42:1: error: control reaches end of non-void function [Werror=return-type]
}
^
cc1plus: some warnings being treated as errors
【问题讨论】:
-
你需要返回一个整数,因为你的函数原型是这样说的。我认为信息很明确。
-
是的,但是(return head->data)是一个整数。
-
你在哪里
return有什么事吗?您确实知道return声明吗?也许你应该read a couple of good books? -
您的函数需要在每个 if 条件下都返回一个整数,或者您可以简单地在函数末尾返回一个整数。这里的问题是编译器认为当条件 if(p== positionFromTail) 永远不会为真时没有返回任何内容。
标签: c function return return-value return-type