2017-05-21 71 views
0
package LinkedList; 

public class LinkedList { 

public class Node { 
    Object data; 
    Node next; 
    //Constructor of Node 
    Node(Object data){ 
     this.data = data; 
    } 
    //getter 
    Object getdata(){ 
     return this.data; 
    } 
    Node getnext(){ 
     return this.next; 
    } 
    //setter 
    void setnext(Node n){ 
     this.next = n; 
    } 
} 

Node header = null; 
int size = 0; 
//Constructor of LinkedList 
public LinkedList(){}; 
//return size 
int size(){ 
    return size; 
} 
//return that list is empty or not 
boolean isEmpty(){ 
    if (size != 0){ 
     return false; 
    } 
    return true; 
} 
Object first(){ 
    return header.getdata(); 
} 
Object Last(int size){ 
    Node c; 
    for(int i=0 ;i<size-1 ;i++){ 
     c = header.getnext(); 
     if (i == size-2){ 
      Object returndata = c.getdata(); 
      return returndata; 
     } 
    } 
} 

} 

first()函數在eclipse上沒有任何錯誤。 但在last()函數,我得到的錯誤是這個方法必須返回一個Object類型的結果。如何解決這個錯誤?此方法必須返回類型結果對象

回答

1

問題是Last()並不總是返回一個值,即使它聲稱。每條代碼路徑都必須返回。

Object Last(int size){ 
    Node c; 
    for(int i=0 ;i<size-1 ;i++){ 
     c = header.getnext(); 
     if (i == size-2){ 
      Object returndata = c.getdata(); 
      return returndata; 
     } 
    } 
    return null; 
} 
1

您還必須在for循環之外還有return語句。你所擁有的只有在執行循環並滿足條件時纔會運行。

如果沒有任何東西可以返回到循環之外,請添加return null;作爲最後一條語句。

相關問題