2013-05-12 132 views
1

Sup球員,所以我要通過我的鏈接列表類中的一些方法,並且從鏈接列表中刪除節點時出現邏輯錯誤。當我在removeLast()方法中遇到錯誤時,我正在處理removeFirst()方法。問題是兩個都刪除列表中的最後一個項目。不知道爲什麼,但這裏是我的代碼。如何刪除鏈接列表中的第一個節點?

刪除第一個節點

public T removeFirst() throws EmptyCollectionException 
{ 
// Checking to see if the List is empty or not 
    if (isEmpty()) 
     throw new EmptyCollectionException("LinkedList"); 

    Node <T> temp = contents; 

    T next = contents.getNext().getItem(); 

    contents = new Node (next, contents); 
    count--; 

    return temp.getItem(); 
} 



刪除最後一個節點

public T removeLast() // fixed 
{ 
// Checking to see if the List is empty or not 
    if (isEmpty()) 
     throw new EmptyCollectionException("LinkedList"); 

    // Node<T> temp = contents; 
    Node<T> current = contents; 
    Node<T> prev = null;   

    while (current.getNext() != null) 
    { 
     prev = current; 
     current = current.getNext(); 
    } 

    prev.setNext(null); 

    count--; 

    return current.getItem(); 

} 

我看了看周圍已經發布的問題,但我似乎無法找到答案我在找。
我知道一個節點至少有兩個值
一個來保存數據,另一個保持參考到下一個節點

這就是我想是怎麼回事了第一位。但是當我一個接一個地調用這些方法時,他們都擺脫了最後一個節點。 Idk我會查看我的代碼並在必要時更新此問題。但是,你們能否看到我要出錯的地方,並指出我朝着正確的方向前進。謝謝。

回答

2

如果您有一個列表A-> B-> C,A是您的列表頭(「內容」),爲了將其刪除,您只需將指針前移到B即下一個節點在您的列表:

public T removeFirst() throws EmptyCollectionException { 
    // Checking to see if the List is empty or not 
    if (isEmpty()) 
     throw new EmptyCollectionException("LinkedList"); 

    Node<T> first = contents; 

    contents = contents.getNext(); 
    count--; 

    return first.getItem(); 
} 

因爲你還需要返回與第一節點相關聯的數據,你需要一個臨時參考保持它。 (我叫它first

+0

謝謝你對removeFirst()的完美工作。出於某種原因,我認爲我需要一個新的節點,因此首先獲取第二個節點中的Item,然後將其鏈接到列表的其餘部分。你的方法要簡單得多。我想我明白了爲什麼我要在removeLast()中再次返回第一個節點。 xD – Raw415 2013-05-12 12:45:18

0

我想你需要添加頭節點到你喜歡的列表類中定義列表的第一個節點。

public void deleteFront() 
{ 
if (head!=null) 
head = head.Next; 
} 
+0

謝謝。這也起作用。 – Raw415 2013-05-12 12:51:12

2
public void removeFirst() { 
     if (head == null) 
       return; 
     else { 
       if (head == tail) { 
        head = null; 
        tail = null; 
       } else { 
        head = head.next; 
       } 
     } 
    } 
0
public T removeFirst() throws EmptyCollectionException { 
if (isEmpty()) 
    throw new EmptyCollectionException("LinkedList"); 

Node <T> temp = contents; 

T next = contents.getNext().getItem(); 

contents = new Node (next, contents); 
count--; 



    return temp.getItem(); 
} 

在這種方法中的註釋最後三個聲明。然後添加下面三行

contents=contents.getNext() 
count--; 
return next; 

刪除最後一個節點:它看起來很好。