2016-11-09 26 views
-1
int last(Node *head) // complete this, must be recursive 
{ 
    Node *ptr = head; 
    if (ptr != NULL) { 
     if (ptr->next == NULL) 
      return ptr->num; 
     else 
      last(ptr->next); 
    } 
} 

我想返回最后一个值,并且我有一种感觉问题与我尝试返回值的方式有关,但我不确定我应该如何去做。以递归方式返回链接列表中的最后一个值的值

+3

'else last(ptr-> next);' - >'else return last(ptr-> next);'。 –

+2

也许读取警告可以帮助在这些情况下 –

+0

改变后返回(ptr-> next);我得到的错误:警告:控制达到非void函数结束[-Wreturn-type] } – garrett1027

回答

2
int last(Node *current) 
{ 
    // degenerate case 
    if (current == NULL) return 0; //or pick another number if you want 

    // last element found 
    if (current->next == NULL) return current->num; 

    // recursive 
    return last(current->next); 
}