2016-02-13 62 views
0

我試圖爲一個類的任務實現雙向鏈表。我目前堅持實施一種方法來刪除指定索引處的節點。實施一個雙向鏈表的刪除方法

public void remove(int index) { 
    if (index < 0 || index > count-1) { 
     throw new ListIndexOutOfBoundsException("The index "+index+" is out of bounds."); 
    } 
    if (isEmpty()) { 
     System.out.println("List is empty"); 
     return; 
    } 

    MedicationNode curr = head; 
    int k = 0; 
    while(k < index) { 
     curr = curr.next; 
     k++; 
    } 
    if (curr.prev == null) { 
     curr.next.prev = null; 
    }else if(curr.next == null) { 
     curr = curr.prev; 
     curr.next = null; 
    }else{ 
     curr.next.prev = curr.prev; 
     curr.prev.next = curr.next; 
    }   
    count--; 
} 

方法可以刪除任何指定的節點在鏈表除了指數爲0。我想這個問題可能是我的add方法,但即時通訊真的不知道。

+0

您必須以特定方式處理第一個元素,因爲在這種情況下,您必須更改'head'變量。 – Seelenvirtuose

回答

1

在你的第一個,如果條件 -

if (curr.prev == null) { 
    curr.next.prev = null; 
    //Make your head of the linked list point to this node 
    head = curr.next; 
} 

這是因爲你從列表中刪除的頭,使頭應指向頭的下一個節點。

+0

工作正常!非常感謝你 – kevinsangabriel

+0

請將答案標記爲接受,如果它工作。 –