交换 LinkedList 中的元素 [英] Swap elements in LinkedList

查看:33
本文介绍了交换 LinkedList 中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保持添加到列表中的元素的顺序.所以,我在 Java 中使用了 LinkedList.

I want to maintain order of the elements being added in a list. So, I used a LinkedList in Java.

现在我希望能够交换链表中的两个元素.首先,我找不到 LinkedListelementAt().此外,无法在指定位置添加元素.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆