交换 LinkedList 中的元素 [英] Swap elements in LinkedList
问题描述
我想保持添加到列表中的元素的顺序.所以,我在 Java 中使用了 LinkedList
.
I want to maintain order of the elements being added in a list. So, I used a LinkedList
in Java.
现在我希望能够交换链表中的两个元素.首先,我找不到 LinkedList
的 elementAt()
.此外,无法在指定位置添加元素.
Now I want to be able to swap two elements in the linked list. First of all, I cannot find an elementAt()
for LinkedList
. Also, there is no way to add element at a specified position.
推荐答案
有一个 Collections.swap(List> list, int i, int j)
可以用来交换 List>
的两个元素.还有 LinkedList.get(int index)
和 LinkedList.add(int index, E element)
(都是接口列表
).所有这些操作都将是 O(N)
,因为 LinkedList
不实现 RandomAccess
.
There is a Collections.swap(List<?> list, int i, int j)
that you can use to swap two elements of a List<?>
. There's also LinkedList.get(int index)
and LinkedList.add(int index, E element)
(both are methods specified by interface List
). All of these operations will be O(N)
since a LinkedList
does not implements RandomAccess
.
这篇关于交换 LinkedList 中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!