简体   繁体   中英

Get node value in linkedlist from end in c

I am doing this hackerrank question ( https://www.hackerrank.com/challenges/get-the-value-of-the-node-at-a-specific-position-from-the-tail ) My code is as follows -

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;
    }
  } 
}

So what i have done is, I have first reversed the linkedlist and then looped for the specific position and then printed its value. Is it correct method to do it? It gives me this error.

  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

The problem statement makes it impossible for the code to reach the end of your function without returning a value, because of this constraint:

Constraints

Position will be a valid element in linked list.

However, C compiler has no idea that your while loop would never exit upon reaching NULL , guaranteeing that return head->data is eventually executed, so it issues an error.

You can fix this by providing an unused return at the end, or by making your loop infinite.

Note: Your solution reverses the list, which may be non-optimal. You can avoid reversal by storing positionFromTail + 1 trailing items in an array as you traverse the list once:

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];
}

Each possible branch which might leave the function needs to return a value.

If the initial head->next would be NULL the return statement you coded would not be reached.

Design your code to have a function have only one possible exit-point.

This might look like the following:

/* 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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