Java 如何交换LinkedList中的两个元素?

Java 如何交换LinkedList中的两个元素?,java,linked-list,swap,Java,Linked List,Swap,如何在Java中交换LinkedList中的两个元素? 假设: LinkedList ttt=新建LinkedList(); ttt.添加(1); ttt.添加(2); ttt.添加(4); //等等。。。。。。。。 如何交换2和3?链接列表只是列表抽象数据类型(ADT)的实现,而列表ADT具有所有相同的方法,无论实现是链接列表还是数组列表 因此,您可以在链接列表中交换2和3,就像在数组列表中交换2和3一样: List<Integer> listOfNumbers = new Li

如何在Java中交换
LinkedList
中的两个元素? 假设:

LinkedList ttt=新建LinkedList();
ttt.添加(1);
ttt.添加(2);
ttt.添加(4);
//等等。。。。。。。。

如何交换2和3?

链接列表只是
列表
抽象数据类型(ADT)的实现,而列表ADT具有所有相同的方法,无论实现是
链接列表
还是
数组列表

因此,您可以在
链接列表中交换2和3,就像在
数组列表中交换2和3一样:

List<Integer> listOfNumbers = new LinkedList<>(Arrays.asList(1, 2, 4, 5, 3, 6));
int twoIndex = listOfNumbers.indexOf(2);
int threeIndex = listOfNumbers.indexOf(3);
listOfNumbers.set(twoIndex, 3);
listOfNumbers.set(threeIndex, 2);
listofNumber=newLinkedList(Arrays.asList(1,2,4,5,3,6));
int twoIndex=ListofNumber.indexOf(2);
int threeIndex=ListofNumber.indexOf(3);
集合(两个索引,3);
集合(三个索引,2);

Rosy,你自己有没有努力解决这个问题?请访问并特别阅读。您需要自己尝试解决方案,并询问是否遇到问题。所以这不是一个代码编写服务。你是说LinkedList吗?是的,我自己尝试过。我创建了一个新的类节点,并使用了prev和next,使用了LinkedList head和all的概念。但是我被告知要用一种更简单的方式来做,我不能这样做。在LinkedList中,你不能像在数组中那样直接做。所以??
List<Integer> listOfNumbers = new LinkedList<>(Arrays.asList(1, 2, 4, 5, 3, 6));
int twoIndex = listOfNumbers.indexOf(2);
int threeIndex = listOfNumbers.indexOf(3);
listOfNumbers.set(twoIndex, 3);
listOfNumbers.set(threeIndex, 2);