简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM