Reputation: 739
Is there a way to switch two elements in a linked list without removing and reinserting them? The code I am currently using is:
void exchange(int i, int j) {
int[] temp = matrix.get(i);
matrix.remove(i);
matrix.add(i, matrix.get(j - 1));
matrix.remove(j);
matrix.add(j, temp);
}
where matrix
is my linked list.
Upvotes: 6
Views: 3549
Reputation: 48659
If you must implement it yourself, this will work:
void exchange(int i, int j) {
ListIterator<int[]> it1 = matrix.listIterator(i),
it2 = matrix.listIterator(j);
int[] temp = it1.next();
it1.set(it2.next());
it2.set(temp);
}
as will this:
void exchange(int i, int j) {
matrix.set(i, matrix.set(j, matrix.get(i)));
}
The second is similar to how Collections.swap
is implemented. The first is slightly more efficient for a long linked list.
Upvotes: 4
Reputation: 23639
Use the swap method in the Collections object: http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int%29
Upvotes: 5