获取节点值从最终在C
问题描述:
我这样做hackerrank问题(https://www.hackerrank.com/challenges/get-the-value-of-the-node-at-a-specific-position-from-the-tail) 我的代码如下 -获取节点值从最终在C
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
答
每个可能离开函数的分支都需要返回一个值。
如果初始的head->next
应该是NULL
那么您编码的return
语句将不会被达到。
设计你的代码使函数只有一个可能退出点。
这可能看起来如下:
/* returns pay-load or INT_MIN if list is empty or searched pos is negativ*/
int GetNode(Node *head, int positionFromTail)
{
int result = INT_MIN;
...
while (head->next != NULL) {
if(p == positionFromTail) {
result = head->data;
break;
}
else {
p++;
head = head->next;
}
}
return result;
}
答
问题陈述使它不可能的代码,达到你的函数结束时不返回值,因为这个约束:
约束条件
位置将是链接列表中的有效元素。
然而,C编译器不知道你while
循环将最终执行在到达NULL
,保证return head->data
永远不会退出,所以它发出一个错误。
您可以通过在末尾提供未使用的return
或通过使循环无限来解决此问题。
注意:您的解决方案反转列表,这可能是非最佳的。您可避免在阵列中存储positionFromTail + 1
尾随项目逆转你遍历列表一次:
int GetNode(Node *head,int positionFromTail) {
int data[++positionFromTail], p = 0;
while (head) {
data[p] = head->data;
head = head->next;
p = (p+1) % positionFromTail;
}
return data[p];
}
需要,因为你的函数的原型是这么说的,返回一个整数。我认为这个信息很清楚。 –
是的,但(return head-> data)是一个整数。 – shreyaa
你在哪里***'return' ***什么?你*知道'return'语句吗?也许你应该[读几本好书](http://*.com/questions/562303/the-definitive-c-book-guide-and-list)? –