繁体   English   中英

从c中的结尾获取链表中的节点值

[英]Get node value in linkedlist from end in c

我正在做这个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

由于以下限制,问题语句使代码无法在不返回值的情况下到达函数末尾:

约束

位置将是链表中的有效元素。

但是,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];
}

每个可能离开函数的分支都需要返回一个值。

如果初始head->nextNULL则不会到达您编码的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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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