2012-11-14 149 views
-2

我對java和我想實現從雙鏈表中刪除方法,但我掙扎,不知道如何推進。該方法刪除存儲在列表中給定節點的數據。我已經讀過,我需要說明被刪除元素是開始還是結束的情況,但我不知道如何去做。總的來說,我不確定這是否是正確的做法。我的代碼/進度在下面發佈。如果有任何可以幫助,它將不勝感激。謝謝從雙向鏈表中刪除

P.S.我有一個開始和類內的端基準和一個大小的參考

public type removeAtTheIndex(int index) 
    { 
    type theData = null; 
    Node <type> current= start; 
    Node temp= new Node(); 
    if (index >= 0 && index < size && start !=null) 
    { 

     for (int i=0; i < index && current.getNext()!= null; i++) 
     { 
      current=current.getNext(); 
     } 
     if (current != null) 
     { 
     if (current == start) 
     { 

     } 

     else if (current == end) 
     { 

     } 

     else 
     { 
      theData= current.getData(); 
      temp= current.getPrev(); 
      temp.setNext(current.getNext()); 
      current.getNext().setPrev(temp); 
      current.setData(null); 
      size--; 

     } 

    } 

    return theData; 
} 
+0

爲什麼不使用[LinkedList](http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html)? – Kai

+0

@ user714965我想通過創建我自己的方式來學習,因此我可以進一步研究。不過謝謝你的建議。你有沒有機會知道我的代碼有什麼問題?謝謝 –

+0

當提供代碼時,它應該是可編譯的。你的代碼有什麼問題?您可以查看LinkedList的源代碼以獲得更好的理解。 – Kai

回答

1

我已經改變了typeType。 Java中不推薦使用小寫字母來命名類名。我已經添加了大量的評論,希望你能理解正在發生的事情。

請注意,這不是測試代碼。您可能會發現錯誤,但我相信流程的本質就在那裏。

public Type removeAtTheIndex(int index) { 
    // I want to return the data that was removed. 
    Type theData = null; 
    // Sanity checks. 
    if (index >= 0 && index < size && start != null) { 
    // Find the entry with the specified index. 
    Node<Type> current = start; 
    for (int i = 0; i < index && (current = current.getNext()) != null; i++) { 
    } 
    // Did we find it? 
    if (current != null) { 
     // Yes! Gather the contents. 
     theData = current.getData(); 
     // Clear it. 
     current.setData(null); 
     // Special? 
     if (current == start) { 
     // Its the start one. 
     start = start.getNext(); 
     // Detach it. 
     start.setPrev(null); 
     } else if (current == end) { 
     // Step end back one. 
     end = end.getPrev(); 
     // Detach it. 
     end.setNext(null); 
     } else { 
     // Remove from within list. 
     Node prev = current.getPrev(); 
     // Point it at my next. 
     prev.setNext(current.getNext()); 
     // Point my next to new prev. 
     current.getNext().setPrev(prev); 
     } 
     // One less now. 
     size--; 
    } 
    } 
    return theData; 
} 
+0

非常感謝!將接受 –

+0

沒問題 - 請也理解。 :) – OldCurmudgeon