2013-09-30 28 views
0

所以如果我想編寫方法Removelast(),這是否工作?這是爲linkedListDS我可以有一個如果沒有別的?我想編寫一個鏈表並使用它(通過組合)構建一個堆棧和一個隊列類

public E removeLast() { 
    E result;   
    if(this.isEmpty())   
    {    
     System.out.println("No data present");    
     return null;   //over here 
    }   

    result = tail.data;   
     if(this.size() == 1)   
     {    
      head= null;    
      tail= null;   
     }   
     else   
     {    
      Node<E> current;    
      current = head;        
      while(current.next != tail)     
       current= current.next;            

      tail = current;    
      tail.next=null;   
     } 

     return result;  
} 
+0

當然,你可以檢查語法的if語句很容易在你的擁有。儘管如此,如果您正在尋找一個實際的語法說明,那麼有很多資源,請使用[Java Precisely](http://www.itu.dk/~sestoft/javaprecisely/javaprecisely-online.pdf)。第42頁 – clwhisk

回答

0

使用if沒有別的是正確的。請注意,這裏有不同風格的編程。你可能想看看這本經典書:Code Complete: A Practical Handbook of Software Construction, Second Edition。我爲自己使用,如果只是爲了劃分程序流,我沒有許多頂級獨立ifs(而不是使用'else if')。

您的代碼中也存在問題。如果你的列表是空的(size()== 0),你試着走節點,這應該給你一個空指針異常。

此外,如果你有一個鏈接列表,其中每個節點存儲一個鏈接到一個節點,你可以通過做刪除尾:

`Node<E> toRemove = tail; 
tail = toRemove.previous; 
if(tail == null) 
    head = null; 
toRemove.previous = null;` 
相關問題