开发者

Java Linked List: Removing Largest Element Using Iterator

how can I remove the largest element from a linkedlist in java? I know I can use get() or remove() functions to retrieve / remove the elements. But I want to make it efficient. I want to use iterator. Do you have any idea how i can do it? Note that I dont want to create my own linkedlist. I dont even want to sort my linkedlist.

Can开发者_如何转开发 I do a linear search for this? If so, how can I keep track of the pointer (or iterator) that points to the largest element. Any help will be appreciated.


A linked list (unless sorted) is not the best structure for what you are trying to do here as you have no other option than do a linear search and remove the biggest element

Integer biggest = Integer.MIN_VALUE;
for(Integer e : myList){
   if(biggest < e)
        biggest = e;
}
myList.remove(biggest);

this would be O(n), even though you have to scan again to remove the biggest, this second scan would be avoidable if you did your own LinkedList because the java.util.LinkedList hides its Entry class and does not allow you to modify the pointers; but that would be the wrong way to optimize, because if instead you use a heap like structure, in java that would be PriorityQueue class, you could get O(log(n)) and reduce the code to:

return myPriorityQueue.poll();


if you know what the largest element is you can do it like so

Iterator<Integer> it = list.iterator();
Integer toRemove;
while(it.hasNext()){
    if(toRemove.compareTo(it.next()==0){
       it.remove();
       break;
    }
}

or use list.removeFirstOccurrence(toRemove)

but LinkedList implementations don't allow for copying iterators to point to specific elements for later removal

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜