2014-11-09 71 views
0

[3,5,4,2,1]我需要刪除靠近尾部的節點,它應該像[1,2,3,5,4]有什麼建議?重複單鏈表

public void delete() { 
    for(Node<T> current = getHead(); current != null; current = current.getNext()){ 

       System.out.println(temp.getValue()); 
       removeValue(temp.getValue()); 
      } 
     } 
    } 
} 
+1

它看起來像你的算法是'爲O(n^3)'因爲它做了一堆不必要的操作。首先,你應該使用迭代器而不是'removeValue()'。 – irrelephant 2014-11-09 00:54:41

+0

那麼這將如何幫助。由於removeValue()是刪除特定值的方法,我只需要從尾部開始刪除。 – user4186509 2014-11-09 00:56:51

+0

我剛剛使用了一個迭代器,並將removeValue()方法放在裏面 – user4186509 2014-11-09 01:00:42

回答

1

你並不需要刪除所有東西(我的意思是不是通過調用removeValue)。只需將您遇到的值存儲在一個集合中,並且如果該值已經在集合中,則重新鏈接您的列表。如果您沒有使用庫代碼的權利,請使用二叉搜索樹實現您的集合,這將非常簡單且非常高效。

這是我會怎麼做,假設我有Set實現:

public void makeUnique() { 
    Set<T> set  = new MySet<>(); 
    Node<T> current = getHead(); 
    Node<T> previous = null; 
    while (current != null) { 
     // if current.getValue() is already in the set, we skip this node 
     // (the add method of a set returns true iff the element was not 
     // already in the set and if not, adds it to the set) 
     if (set.add(current.getValue()) { 
      // previous represents the last node that was actually inserted in the set. 
      // All duplicate values encountered since then have been ignored so 
      // previous.setNext(current) re-links the list, removing those duplicates 
      if (previous != null) { 
       previous.setNext(current); 
       current.setPrevious(previous); 
      } 
      previous = current; 
     } 
     current = current.getNext(); 
    } 
}