简体   繁体   English

Java链接列表:使用迭代器删除最大的元素

[英]Java Linked List: Removing Largest Element Using Iterator

how can I remove the largest element from a linkedlist in java? 如何从java中的链表中删除最大的元素? I know I can use get() or remove() functions to retrieve / remove the elements. 我知道我可以使用get()或remove()函数来检索/删除元素。 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; 这将是O(n),即使您必须再次扫描以删除最大的,如果您执行自己的LinkedList,则第二次扫描将是可以避免的,因为java.util.LinkedList隐藏其Entry类并且不允许您修改指针; 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: 但这将是错误的优化方式,因为如果你使用类似堆的结构,在java中将是PriorityQueue类,你可以获得O(log(n))并将代码减少到:

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) 或使用list.removeFirstOccurrence(toRemove)

but LinkedList implementations don't allow for copying iterators to point to specific elements for later removal 但LinkedList实现不允许复制迭代器以指向特定元素以便以后删除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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