2013-10-19 68 views
0

的方法刪除對象表單列表我試圖使用具有特定索引的方法從列表中刪除一個對象,該方法需要刪除特定索引。這裏棘手的部分是這個列表是一個雙鏈表,當我從它中刪除一個節點時,下一個和上一個指針需要重定向到正確的節點。 這是我到目前爲止,但代碼似乎沒有正確重定向指針,我會appriciate任何投入!使用帶參數

private static final class Node<T>  
    { 
    private T value; 
    private Node<T> previous, next; 

    private Node(T value, Node<T> previous, Node<T> next) // constructor 
    { 
     this.value = value; 
     this.previous = previous; 
     this.next = next; 
    } 
    } 

    private Node<T> head;   // first in the list 
    private Node<T> tale;   // last in the list 






public T remove(int index) { 
     indexcontrol(index); // checks if legal index 

     Node<T> q, p = null; 

     if(index == 0) 
     { 
      q = head; 
      head = head.next; 
     } 

     else 
     { 
      p = findNode(index-1); // finds the nodes value on place index 
      q = p.next; 

      p.next= q.next; 
     } 

     if (q== tale) tale = p; 

     T value = q.value; 
     q.value = null; 

     q.next = null; 

     return value; 

    } 
+0

如果你刪除元素,爲什麼你不讓你的方法'void'? – qiGuar

+0

即時通訊在另一種方法中使用返回值 – comodeque

回答

0

您需要將上一個和下一個指針分配給正確的節點。

public T remove (int index){ 
    if (index==0){ 
     //remove head 
    }else if (index == size){ 
     //remove tail 
    } 
    else { 
     Node<T> p = null; 
     Node<T> q = null; 
     Node<T> r = null; 
     p = findNode(index-1); // finds the nodes previous to the node that needs to be removed 
     q = p.next; //q is the node you want to remove 
     r = q.next; //r is the node next to the node you want to remove 

     p.next = r; 
     r.previous = p; 

     //you can explicitly delete the node, but GC will collect anyway. 
     q.next = null; 
     q.previous = null; 
     T value = q.value; 
     q.value = null; 
     return value; 
    } 
} 
+0

感謝所有的答案,它現在是有道理的! – comodeque

0

看來,在else聲明中,只需更改其中一個指針即可。應該是這樣的:

prevNode.next = origNode.next; 
nextNode.prev = origNode.prev;