Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

java - Swap elements in LinkedList

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...