简体   繁体   English

反转 java.util.LinkedList 的最佳方法(如果可能的话)

[英]Best way to reverse a java.util.LinkedList (in place if possible)

I want to reverse a java.util.LinkedList<Integer> using the available methods.我想使用可用的方法反转java.util.LinkedList<Integer>
Looking in the methods provided and the Iterators I couldn't see an option other than the following:查看提供的方法和Iterators我看不到除以下内容之外的其他选项:

int i = list.size();  
int pos = 0;  
while(i-- > 1){  
     Integer n = list.removeLast();  
     list.add(pos++, n);          
} 

But surely there must be a better way.但肯定必须有更好的方法。 I mean it is not a good idea to modify a list outside of an iterator, but I couldn't see how I could use one here without having to create a new list.我的意思是在迭代器之外修改列表不是一个好主意,但我不知道如何在这里使用一个列表而不必创建一个新列表。
Is there a better way?有没有更好的办法?

使用 import java.util.Collections;

Collections.reverse(list);

There's an api method for that.有一个 api 方法。

Collections.reverse(yourList);

See http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#reverse%28java.util.List%29 .请参阅http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#reverse%28java.util.List%29

If for some reason you want to do it yourself, this seems the best way:如果出于某种原因你想自己做,这似乎是最好的方法:

List<T> reversed = new LinkedList<T>();
while(!yourList.isEmpty()) reversed.add(yourList.removeLast());

We can reverse Linkedlist in java by these ways我们可以通过这些方式在java中反转Linkedlist

  1. Using collections - We can reverse list in java with the help of reverse() method of collections使用集合 - 我们可以在集合的 reverse() 方法的帮助下反转 Java 中的列表

    LinkedList<String> linkedList = new LinkedList<String>(); linkedList.add("Mumbai"); linkedList.add("Delhi"); //print linkedlist //Reverses the order of the elements in the specified list. Collections.reverse(linkedList);
  2. Using List.set() method We will swap element of list first to end .使用 List.set() 方法我们将首先交换列表的元素到 end 。 so on using below logic所以使用下面的逻辑

     for(int i = 0, mid = list.size()/2, j = list.size() - 1; i < mid; i++, j--) list.set(i, list.set(j, list.get(i)));//swap element }

Reference : How to reverse elements of LikedList参考: 如何反转 LikedList 的元素

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

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