2017-09-26 128 views
0

我試圖從列表中移除遊標並使其引用前一個CarListNode(或者頭部,如果遊標先前引用了該列表的頭部)。同時仍然返回光標內的信息。 我的代碼無法正確刪除遊標。我的代碼中有什麼問題?從雙向鏈表中刪除遊標

這裏是我當前的代碼:

public Fruit removeCursor() throws EndOfListException { 

    if (cursor == null) { 
     throw new EndOfListException(); 

    } else if (cursor.getPrev() == null) { 
     head = cursor.getNext(); 
     cursor.setNext(null); 
     cursor.setPrev(null); 
     cursor = head; 

    } else if (cursor.getNext() == null) { 
     tail = cursor.getPrev(); 
     cursor.setPrev(null); 
     cursor.setNext(null); 
     cursor = tail; 

    } else { 
     cursor.setData(cursor.getNext().getData()); //this isn't a singly linked list 
     cursor.setNext(cursor.getNext().getNext()); 
    } 

    count--; 

    return cursor.getData(); 
} 
+0

什麼是你的問題? –

+0

對不起,深夜。我只是問我的代碼有什麼問題,因爲遊標並未在預期中被刪除。 –

+0

*我的代碼無法正確刪除遊標。我的代碼中有什麼問題?*誰知道遊標是什麼,直到你告訴它, – nullpointer

回答

0

else條款並不 「刪除光標」 ......

嘗試是這樣的:

else { 
    cursor.getPrev().setNext(cursor.getNext()); 
    cursor.getNext().setPrev(cursor.getPrev()); 
    // You might want to release the cursor's item, EG: 
    cursor = null; 
    cursor = cursor.getNext(); 
}