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

查看:211
本文介绍了在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) (两者都是<指定的方法a href =http://java.sun.com/javase/6/docs/api/java/util/List.html =noreferrer> interface List )。所有这些操作都是 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天全站免登陆