用運行速度最優的方法從LinkedList列表里刪除重復的元素,例如A->B->BB->B->C,返回A->B->BB->C。
考試的時候沒完全想明白,考完又想了想,其實還是蠻簡單的。思路很簡單:利用一個Set存放LinkedList中的元素,在迭代的過程中,判斷當前元素是否在Set中出現過,如果出現過就刪除,也就是說我們在遍歷的過程中進行刪除操作,所以這里要用到ListIterator,而不能用普通的Iterator。
代碼如下:
private static LinkedList removeDuplicatedElements(LinkedList list) { HashSet set = new HashSet(); Iterator iter = list.listIterator(); while(iter.hasNext()){ String str = (String)iter.next(); if(!set.contains(str)) set.add(str); else iter.remove(); } return list; }
http://www.tuicool.com/articles/MrYZZb